简体   繁体   English

如果值不存在或检查 DynamoDBMapper 中的条件,则更新

[英]Update if value doesn't exist or check condition in DynamoDBMapper

I am working on a method that saves to DynamoDB.我正在研究一种保存到 DynamoDB 的方法。 I want the method to save if the value doesn't exist in the table.如果表中不存在该值,我希望该方法进行保存。 If it does exist, I want to apply a conditional update.如果确实存在,我想应用条件更新。 I am using DynamoDBMapper's save method.我正在使用 DynamoDBMapper 的保存方法。

The code I have at the moment does the conditional save successfully, but throws an exception if the column doesn't exist in the database.我目前的代码成功地进行了条件保存,但如果该列不存在于数据库中,则会引发异常。

Is there a way to come up with a conditional update expression that checks if the value doesn't exist or checks for the condition I need?有没有办法提出一个条件更新表达式来检查值是否不存在或检查我需要的条件?

The code I have at the moment, which is in Java, looks like this:我目前拥有的代码是 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);

Thanks!谢谢!

The ExpectedAttribute stuff is there for Legacy applications ( https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html#DDB-PutItem-request-Expected ). ExpectedAttribute 内容适用于旧版应用程序 ( https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html#DDB-PutItem-request-Expected )。

It's recommended that you use the newer ConditionExpression instead.建议您改用较新的 ConditionExpression。

This is one way i've done it, although the snippet below is converted from Scala code and untested.这是我完成的一种方式,尽管下面的代码片段是从 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM