如何通过复合主键在Dynamodb
问题描述:
更新项目我有一个表叫朋友:如何通过复合主键在Dynamodb
Friend 1 | Friend 2 | Status
朋友1是我的HASH属性和朋友2是我的范围属性。
我想更新一个项目的staus属性,其中朋友1 ='Bob'和朋友2 ='Joe'。阅读有关http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPICRUDExample.html的文档,我只能看到如何通过1个键更新项目,我如何包含另一个键?
答
我正在写示例,您可以在单个表中更新多个项目。我有主键作为ID和范围键作为日期时间。 实际上在dynamodb中没有可用的功能,所以我在这里做的是首先查询所有变量,并使用其中我想更新的哈希键和范围键。一旦所有数据存储在列表中,然后使用散列键和范围键加载数据并使用设置更改或更新字段并保存它。 因为我在散列键编辑,所以散列键原来将在那里,我们需要删除它。如果你需要在下一个属性中更新不需要。我没有添加删除代码自己写。你可以查询你是否混淆了你的条目,散列键仍然会被添加,并且新的散列键将被添加。 代码如下:
public static void main(String[] args) {
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
DynamoDBMapper mapper = new DynamoDBMapper(client);
client.setEndpoint("http://localhost:8000/");
String fromDate = "2016-01-13";
String toDate = "2016-02-05";
User user = new User();
user.setId("YourHashKey");
LocalDate frmdate = LocalDate.parse(fromDate, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate todate = LocalDate.parse(toDate, DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime startfrm = frmdate.atStartOfDay();
LocalDateTime endto = todate.atTime(23, 59, 59);
Condition rangeCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN.toString()).withAttributeValueList(new AttributeValue().withS(startfrm.toString()), new AttributeValue().withS(endto.toString()));
DynamoDBQueryExpression<User> queryExpression = new DynamoDBQueryExpression<User>().withHashKeyValues(user).withRangeKeyCondition("DATETIME", rangeCondition);
List<User> latestReplies = mapper.query(User.class, queryExpression);
for (User in : latestReplies) {
System.out.println(" Hashid: " + in.getId() + " DateTime: " + in.getDATETIME() + "location:" + in.getLOCID());
User ma = mapper.load(User.class, in.getId(), in.getDATETIME());
ma.setLOCID("Ohelig");
mapper.save(ma);
}
}
答
在这里你去:
DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
.withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2")
.withExpressionAttributeValues(
...
其中Id是哈希键和ReplyDateTime是RANGE键。
参考: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.QueryScanExample.html