发布到一个老问题,因为我不认为解决的办法也很容易找到。希望这可以帮助某人。
第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
嘿非常感谢,你的建议解决了我的问题:)。我现在使用你指定的格式。另外,我的印象是HashKey应该是唯一的。感谢澄清。 – Amit 2014-10-01 23:57:31
相对于您的总数据集,Hashkey应该是唯一的。如果你只有五个用户,但你有数百万行,你将遭受性能损失。对于这个特定的用例,主哈希键是非唯一的。如果感兴趣,您可以阅读更多关于Amazon DynamoDB如何对数据进行性能分区的内容。 – kurtzbot 2014-10-02 15:19:28
这个答案是错误的。 DynamoDB表不能包含具有非唯一主键的项目,无论是简单(仅分区键)还是复合(分区键和排序键)。 *分区密钥=散列密钥;排序键=范围键 – golem 2016-12-05 01:33:38