问题
How can i update multiple records in DynamoDB in single query? I have a csv file as an input based on the csv file I have to update multiple records(only one attribute) in the DB. Is there any API available for this? or This can be done using batch processing(Spring-batch)?
回答1:
DynamoDB doesn't have batchUpdate API directly. It does have batch get item and batch write item API.
However, you can use batchWriteItem API to update the item.
1) Use the below BatchWriteItemSpec class to construct the request
BatchWriteItemSpec
2) Use the below TableWriteItems class to construct the item that need to be updated
TableWriteItems
3) Use the below addItemToPut method (or withItemsToPut) to add the new attribute
addItemToPut
The batchWriteItem API creates a new item if the item (i.e. partition key) is not available. If the partition key is available, it will update the existing item. Your use case falls under this category.
Code Sample:-
files - is the the table name
fileName - is the partition key
transcriptionnew - Adding the new attribute (or can update the existing attribute value as well)
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
Item itemUpdate1 = new Item();
itemUpdate1.withKeyComponent("fileName", "file1")
.withString("transcriptionnew", "new value");
Item itemUpdate2 = new Item();
itemUpdate2.withKeyComponent("fileName", "file2")
.withString("transcriptionnew", "new value");
TableWriteItems tableWriteItems = new TableWriteItems("files").withItemsToPut(itemUpdate1, itemUpdate2);
BatchWriteItemSpec batchWriteItemSpec = new BatchWriteItemSpec().withTableWriteItems(tableWriteItems);
BatchWriteItemOutcome batchWriteItemOutCome = dynamoDB.batchWriteItem(batchWriteItemSpec);
if (batchWriteItemOutCome.getUnprocessedItems().isEmpty()) {
//All items are processed
return true;
}
来源:https://stackoverflow.com/questions/43468257/updating-multiple-records-in-dynamodb