DynamoDB API:如何构建"添加JSON属性(如果不存在)"更新请求?

And*_*ell 10 java json amazon-web-services nosql amazon-dynamodb

我正在尝试使用新的Amazon DynamoDB JSON API在名为"document"的JSON属性中添加/覆盖键值对.理想情况下,我想简单地构建我的写调用以发送KV对以添加到属性,并且如果给定主键尚不存在,则让Dynamo创建属性.但是,如果我只是简单地尝试这个UpdateItemSpec:

PrimaryKey primaryKey = new PrimaryKey("key_str", "mapKey");
ValueMap valuesMap = new ValueMap().withLong(":a", 1234L).withLong(":b", 1234L);
UpdateItemSpec updateSpec = new UpdateItemSpec().withPrimaryKey(primaryKey).withUpdateExpression("SET document.value1 = :a, document.value2 = :b");
updateSpec.withValueMap(valuesMap);
table.updateItem(updateSpec);
Run Code Online (Sandbox Code Playgroud)

我明白了com.amazonaws.AmazonServiceException: The document path provided in the update expression is invalid for update,这意味着DynamoDB找不到要应用更新的名为"document"的给定属性.

我设法使用以下一系列调用来近似此功能:

try {
    // 1. Attempt UpdateItemSpec as if attribute already exists
} catch (AmazonServiceException e) {
    // 2. Confirm the exception indicated the attribute was not present, otherwise rethrow it
    // 3. Use a put-if-absent request to initialize an empty JSON map at the attribute "document"
    // 4. Rerun the UpdateItemSpec call from the above try block
}       
Run Code Online (Sandbox Code Playgroud)

这可行,但不太理想,因为每次向表中添加新的主键时都需要3次调用DynamoDB.我尝试了一下attribute_not_exists可以在Update Expressions中使用的函数,但是无法以我想要的方式使它工作.

任何Dynamo大师都有关于如何/是否可以做到的任何想法?

And*_*ell 4

我收到亚马逊支持的答复,实际上不可能通过一次调用来完成此任务。他们确实建议在为新主键添加属性时,通过在 put-if-absent 请求中使用所需的 JSON 映射而不是空映射,将调用次数从 3 个减少到 2 个。

  • 我真的很想在这里看到代码,因为我面临着同样的挑战。DynamoDB API 给我的印象是极其幼稚。 (3认同)