gpt4 book ai didi

java - DynamoDB 表达式 - 多个 ExpectedAttributeValues 比较

转载 作者:行者123 更新时间:2023-11-30 06:54:47 25 4
gpt4 key购买 nike

我正在尝试使用 java sdk 来使用 DynamoDB 的 DynamoDBSaveExpression。

我正尝试模拟以下两种场景:

1) 如果该项目存在于表中,则强制执行保存表达式限制 DATE1、DATE2 和 DATE3(请参阅下面的代码)。

2) 如果表中不存在该项目,则尝试插入它。

这是迄今为止我的代码:

        ExpectedAttributeValue date1 = new ExpectedAttributeValue()
.withComparisonOperator(ComparisonOperator.LE)
.withValue(new AttributeValue().withN(Long.toString(tr.date1().getTime())));

ExpectedAttributeValue date2 = new ExpectedAttributeValue()
.withComparisonOperator(ComparisonOperator.LE)
.withValue(new AttributeValue().withN(Long.toString(tr.date2().getTime())));

ExpectedAttributeValue date3 = new ExpectedAttributeValue()
.withComparisonOperator(ComparisonOperator.LE)
.withValue(new AttributeValue().withN(Long.toString(tr.date3().getTime())));



DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
Map<String, ExpectedAttributeValue> expectedAtributes =
ImmutableMap.<String, ExpectedAttributeValue>builder()
.put("date1", date1)
.put("date2", date2)
.put("date3", date3)
.build();

saveExpression.setExpected(expectedAtributes);
saveExpression.setConditionalOperator(ConditionalOperator.AND);

我不确定如何使用保存表达式来捕获这两种情况。请注意,我知道我可以动态传递单独的保存表达式,但这样做会涉及我的客户不希望进行的重大重构。

最佳答案

尝试以项目不存在为条件进行 UpdateItem 调用,并捕获 ConditionalCheckFailedException。在 catch block 中,您知道该项目存在,因此您可以执行 UpdateItem 调用,该调用以项目存在并满足上述条件为条件。您无法设置attribute_exists conditions使用映射器,因此您需要使用 low-level APIDocument SDK利用此功能。

try {
table.updateItem(new UpdateItemSpec().withPrimaryKey(...)
.withConditionExpression("attribute_not_exists(my_hash_key)")
//one for each attribute of the item you are creating
.withAttributeUpdate(new AttributeUpdate("attribute_name")
.put("attribute_value"))
);
} catch(ConditionalCheckFailedException e) {
table.updateItem(new UpdateItemSpec().withPrimaryKey(...)
.withConditionExpression("attribute_exists(my_hash_key)")
.withUpdateExpression("SET attributeToChange = :val")
.withExpressionAttributeValues(ImmutableMap.of(":val", "asdf"))
);
}

关于java - DynamoDB 表达式 - 多个 ExpectedAttributeValues 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42062365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com