問題描述
新的 AWS DynamoDB 文檔 API 允許直接對應于底層 JSON 表示的 2 種新數據類型:地圖 (又名 JSON 對象)和 List(又名 JSON 數組).
The new AWS DynamoDB document API allows 2 new data types that correspond directly to the underlying JSON representation: Map (aka JSON object) and List (aka JSON array).
但是,我找不到在不完全覆蓋它們的情況下更新這些數據類型的屬性的方法.相反,可以通過添加另一個數字來更新 Number 屬性,因此在 Java 中您可以執行以下操作:
However, I can't find a way to update attributes of these data types without completely overwriting them. In contrast, a Number attribute can be updated by ADDing another number, so in Java you can do something like:
new AttributeUpdate("Some numeric attribute").addNumeric(17);
同樣,您可以addElements 到Set 數據類型的屬性.(在舊 API 中,您可以同時使用 AttributeAction.ADD.)
Similarly you can addElements to an attribute of a Set data type. (In the old API you would use AttributeAction.ADD for both purposes.)
但是對于 Map 或 List,您似乎必須在本地更新以前的值,然后 PUT 代替那個值,例如在 Java 中:
But for a Map or a List, it seems you must update the previous value locally, then PUT it instead of that value, for example in Java:
List<String> list = item.getList("Some list attribute");
list.add("new element");
new AttributeUpdate("Some list attribute").put(list);
這樣的可讀性要差得多,在某些情況下效率要低得多.
This is much less readable, and under some circumstances much less efficient.
所以我的問題是:
有沒有辦法更新 Map 或 List 數據類型的屬性而不覆蓋以前的值?例如,將元素添加到 List,或將元素放入 Map?
Is there a way to update an attribute of a Map or a List data type without overwriting the previous value? For example, to add an element to a List, or to put an element in a Map?
您將如何使用 Java API 實現它?
How would you implement it using the Java API?
您知道將來支持此功能的計劃嗎?
Do you know of plans to support this in the future?
推薦答案
請查看 UpdateItem API
例如給定一個帶有列表的項目:
For example given an item with a list:
{
"hashkey": {"S" : "my_key"},
"my_list" : {"L":
[{"N":"3"},{"N":"7"} ]
}
您可以使用如下代碼更新列表:
You can update the list with code like the following:
UpdateItemRequest request = new UpdateItemRequest();
request.setTableName("myTableName");
request.setKey(Collections.singletonMap("hashkey",
new AttributeValue().withS("my_key")));
request.setUpdateExpression("list_append(:prepend_value, my_list)");
request.setExpressionAttributeValues(
Collections.singletonMap(":prepend_value",
new AttributeValue().withN("1"))
);
dynamodb.updateItem(request);`
您還可以通過反轉 list_append 表達式中參數的順序來追加到列表.
You can also append to the list by reversing the order of the arguments in the list_append expression.
像這樣的表達式: SET user.address.zipcode = :zip
將處理結合表達式屬性值的 JSON 地圖元素 {":zip" : {"N":"12345"}}
An expression like: SET user.address.zipcode = :zip
would address a JSON map element combined with expression attribute values {":zip" : {"N":"12345"}}
這篇關于如何更新 AWS DynamoDB 文檔 API 上的地圖或列表?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!