【问题标题】:Update if value doesn't exist or check condition in DynamoDBMapper如果值不存在则更新或检查 DynamoDBMapper 中的条件
【发布时间】:2017-09-29 21:44:41
【问题描述】:

我正在研究一种保存到 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);

谢谢!

【问题讨论】:

    标签: java amazon-web-services amazon-dynamodb


    【解决方案1】:

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

    建议您改用较新的 ConditionExpression。

    这是我做到的一种方式,尽管下面的 sn-p 是从 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2019-05-12
      • 2021-02-04
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多