[英]How to update item by Composite Primary Key in 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個鍵來更新項目,如何包含另一個鍵?
干得好:
DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>()
.withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2")
.withExpressionAttributeValues(
...
其中,Id是哈希鍵,ReplyDateTime是范圍鍵。
參考: http : //docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.QueryScanExample.html
我正在寫示例,您可以在單個表中更新多個項目。 我有主鍵作為id和范圍鍵作為Datetime。 實際上在dynamodb中沒有可用的功能,因此我在這里首先要查詢所有要進行更新的帶有哈希鍵和范圍鍵的變量。 一旦所有數據存儲在List中,然后使用其哈希鍵和rangekey加載數據,並使用set和save更改或更新字段。 由於我正在編輯哈希鍵,因此哈希鍵原件將存在,我們需要將其刪除。 如果您需要在下一個屬性中進行更新,則不需要。 我還沒有添加刪除代碼,請自行編寫。 您可以查詢是否有混淆,帶有哈希鍵的條目將保持不變,並添加帶有新哈希鍵的新條目。 代碼如下:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.