Java DynamoDB表达式-多个预期属性值比较
我正在尝试使用JavaSDK使用DynamoDB的DynamoDBSaveExpression 我正试图模拟以下两种情况: 1) 如果表中存在该项,请强制执行保存表达式限制DATE1、DATE2和DATE3(请参见下面的代码) 2) 如果表中不存在该项,请尝试插入它 以下是我目前的代码:Java DynamoDB表达式-多个预期属性值比较,java,amazon-web-services,amazon-dynamodb,Java,Amazon Web Services,Amazon Dynamodb,我正在尝试使用JavaSDK使用DynamoDB的DynamoDBSaveExpression 我正试图模拟以下两种情况: 1) 如果表中存在该项,请强制执行保存表达式限制DATE1、DATE2和DATE3(请参见下面的代码) 2) 如果表中不存在该项,请尝试插入它 以下是我目前的代码: ExpectedAttributeValue date1 = new ExpectedAttributeValue() .withComparisonOperat
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);
ExpectedAttributeValue日期1=新的ExpectedAttributeValue()
.withComparisonOperator(ComparisonOperator.LE)
.withValue(新的AttributeValue().withN(Long.toString(tr.date1().getTime()));
ExpectedAttributeValue date2=新的ExpectedAttributeValue()
.withComparisonOperator(ComparisonOperator.LE)
.withValue(新的AttributeValue().withN(Long.toString(tr.date2().getTime()));
ExpectedAttributeValue date3=新的ExpectedAttributeValue()
.withComparisonOperator(ComparisonOperator.LE)
.withValue(新的AttributeValue().withN(Long.toString(tr.date3().getTime()));
DynamoDBSaveExpression saveExpression=新的DynamoDBSaveExpression();
地图期望的贡品=
ImmutableMap.builder()
.put(“日期1”,日期1)
.put(“日期2”,日期2)
.put(“日期3”,日期3)
.build();
saveExpression.setExpected(ExpectedAttributes);
saveExpression.setConditionalOperator(ConditionalOperator.AND);
我不确定如何使用Save表达式捕获这两种情况。请注意,我知道我可以动态地传入一个单独的保存表达式,但这样做会涉及到我的客户机不希望的重大重构。尝试一个UpdateItem调用,使项上的条件不存在,并捕获ConditionalCheckFailedException。在catch块中,您知道该项已存在,因此可以执行UpdateItem调用,以确定该项是否存在并满足上述条件。无法使用映射器进行设置,因此需要使用或来利用此功能
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"))
);
}