我正在研究一种保存到 DynamoDB 的方法。如果表中不存在该值,我希望该方法能够保存。如果确实存在,我想应用条件更新。我正在使用 DynamoDBMapper 的保存方法。
我目前的代码成功地进行了条件保存,但如果数据库中不存在该列,则会抛出异常。
有没有办法提出一个条件更新表达式来检查值是否不存在或检查我需要的条件?
我目前使用 Java 编写的代码如下所示:
DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
AttributeValue attributeValue = new AttributeValue(valueToSave);
ExpectedAttributeValue expectedAttributeValue = new ExpectedAttributeValue(attributeValue).withComparisonOperator(ComparisonOperator.LT);
Map<String, ExpectedAttributeValue> expected = new HashMap<>();
expected.put("key", expectedAttributeValue);
saveExpression.setExpected(expected);
dynamoDbMapper.save(objectToSave);
谢谢!
最佳答案
ExpectedAttribute 内容用于遗留应用程序 (https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html#DDB-PutItem-request-Expected)。
建议您改用较新的 ConditionExpression。
这是我完成的一种方法,尽管下面的代码片段是从 Scala 代码转换而来的并且未经测试。
Map attrVals = new HashMap() {{
put(":revision", new AttributeValue().withN(revision.toString)));
}};
PutItemRequest request = new PutItemRequest().withTableName(myTableName)
.withItem(myItem)
.withConditionExpression(attribute_not_exists(primaryKey) OR revision <= :revision)
.withExpressionAttributeValues(attrVals);
dynamoClient.putItem(request);
关于java - 如果值不存在则更新或检查 DynamoDBMapper 中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46497296/