【问题标题】:How to update item by Composite Primary Key in Dynamodb如何通过 Dynamodb 中的复合主键更新项目
【发布时间】:2015-11-05 07:48:45
【问题描述】:
【问题讨论】:
标签:
amazon-web-services
amazon-dynamodb
【解决方案2】:
我正在编写示例,您可以在其中更新单个表中的多个项目。我有主键作为 id 和范围键作为日期时间。
实际上 dynamodb 中没有可用的功能,所以我在这里做的是首先使用我想要更新的哈希键和范围键查询所有变量。一旦所有数据都存储在 List 中,然后使用它的 hash key 和 rangekey 加载数据,并使用 set 更改或更新字段并保存它。
由于我在哈希键中进行编辑,因此哈希键原始将在那里,我们需要将其删除。如果您需要在下一个属性中更新,则无需。我没有添加自己编写的删除代码。如果您有混淆,您可以查询带有哈希键的条目将仍然存在,并且将添加带有新哈希键的新条目。
代码如下:
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);
}
}