[英]DynamoDB API: How can I build an “add JSON attribute if not present” update request?
I am trying to use the new Amazon DynamoDB JSON API to add/overwrite key-value pairs in a JSON attribute called "document". 我正在尝试使用新的Amazon DynamoDB JSON API在名为“document”的JSON属性中添加/覆盖键值对。 Ideally, I would like simply to structure my write calls to send the KV pairs to add to the attribute, and have Dynamo create the attribute if it does not already exist for the given primary key.
理想情况下,我想简单地构造我的写入调用以发送KV对以添加到属性,并且如果给定主键尚不存在,则让Dynamo创建属性。 However if I try this with just a straightforward
UpdateItemSpec
: 但是,如果我只用一个简单的
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);
I get com.amazonaws.AmazonServiceException: The document path provided in the update expression is invalid for update
, meaning DynamoDB could not find the given attribute named "document" to which to apply the update. 我得到
com.amazonaws.AmazonServiceException: The document path provided in the update expression is invalid for update
,这意味着DynamoDB找不到要应用更新的名为“document”的给定属性。
I managed to approximate this functionality with the following series of calls: 我设法使用以下一系列调用来近似此功能:
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
}
This works, but is less than ideal as it will require 3 calls to DynamoDB every time I add a new primary key to the table. 这可行,但不太理想,因为每次向表中添加新的主键时都需要3次调用DynamoDB。 I experimented a bit with the
attribute_not_exists
function that can be used in Update Expressions , but wasn't able to get it to work in the way I want. 我使用了可以在Update Expressions中使用的
attribute_not_exists
函数进行了一些实验,但是无法以我想要的方式使它工作。
Any Dynamo gurus out there have any ideas on how/whether this can be done? 任何Dynamo大师都有关于如何/是否可以做到的任何想法?
I received an answer from Amazon Support that it is not actually possible to accomplish this with a single call. 我收到亚马逊支持部门的答复,实际上无法通过一次通话完成此操作。 They did suggest to reduce the number of calls when adding the attribute for a new primary key from 3 to 2, by using the desired JSON map in the put-if-absent request rather than an empty map.
通过在put-if-absent请求中使用所需的JSON映射而不是空映射,他们确实建议在将新主键的属性从3添加到2时减少调用次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.