发布到一个老问题,因为我认为解决方案不容易找到。希望这对某人有所帮助。
第 1 步:创建一个反映所需结构的复杂 Java 对象。
List<HashMap<String, Integer>> cartItems = new ArrayList<HashMap<String, Integer>>();
HashMap<String, Integer> item1 = new HashMap<String, Integer>();
item1.put("ProductId", 100);
item1.put("Quantity", 50);
cartItems.add(item1);
HashMap<String, Integer> item2 = new HashMap<String, Integer>();
item2.put("ProductId", 121);
item2.put("Quantity", 51);
cartItems.add(item2);
第 2 步:使用复杂对象更新 DynamoDB 项目。
我使用辅助方法:
private void updateAttribute(int id, String newAttribute, Object newValue){
Map<String, Object> newValues = new HashMap<String, Object>();
newValues.put(":value", newValue);
UpdateItemSpec updateItemSpec = new UpdateItemSpec()
.withPrimaryKey("id", id)
.withUpdateExpression("set " + newAttribute + " = :value")
.withValueMap(newValues);
siteTable.updateItem(updateItemSpec);
}
然后这样调用:
updateAttribute(123, "CartItems", cartItems);
新添加的购物车项目属性在 DynamoDB 中显示如下:
{
"CartItems": [
{
"ProductId": 100,
"Quantity": 50
},
{
"ProductId": 121,
"Quantity": 51
}
]
}
我还没有测试过 upsert 场景。过去,似乎不存在 upsert 功能:https://forums.aws.amazon.com/thread.jspa?threadID=162907
关于深度嵌套项的读取:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html#DocumentPaths