更新特定列时,需要指定要更新的列。假设我们有这张表:
现在假设我们要更新 archive 列。您需要在代码中指定列。这里我们将key对应的item的archive列改为Closed(单列更新)。请注意,我们使用名为 updatedValues 的 HashMap 对象指定列名。
// Archives an item based on the key
public String archiveItem(String id){
DynamoDbClient ddb = getClient();
HashMap<String,AttributeValue> itemKey = new HashMap<String,AttributeValue>();
itemKey.put("id", AttributeValue.builder()
.s(id)
.build());
HashMap<String, AttributeValueUpdate> updatedValues =
new HashMap<String,AttributeValueUpdate>();
// Update the column specified by name with updatedVal
updatedValues.put("archive", AttributeValueUpdate.builder()
.value(AttributeValue.builder()
.s("Closed").build())
.action(AttributeAction.PUT)
.build());
UpdateItemRequest request = UpdateItemRequest.builder()
.tableName("Work")
.key(itemKey)
.attributeUpdates(updatedValues)
.build();
try {
ddb.updateItem(request);
return"The item was successfully archived";
注意:这不是增强型客户端。
此代码来自 AWS 教程,该教程展示了如何使用 Spring Boot 构建 Java Web 应用程序。完整教程在这里:
Creating the DynamoDB web application item tracker
要使用增强型客户端更新单个列,请致电 Table method。这将返回一个DynamoDbTable instance。现在您可以调用 updateItem 方法了。
以下是使用增强型客户端更新 archive 列的逻辑。注意你得到一个 Work 对象,调用它的 setArchive 然后传递 Work 对象。 workTable.updateItem(r->r.item(work));
Java 代码:
// Update the archive column by using the Enhanced Client.
public String archiveItemEC(String id) {
DynamoDbClient ddb = getClient();
try {
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getClient())
.build();
DynamoDbTable<Work> workTable = enhancedClient.table("Work", TableSchema.fromBean(Work.class));
//Get the Key object.
Key key = Key.builder()
.partitionValue(id)
.build();
// Get the item by using the key.
Work work = workTable.getItem(r->r.key(key));
work.setArchive("Closed");
workTable.updateItem(r->r.item(work));
return"The item was successfully archived";
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}
此答案显示了更新 DynamoDB 表中单个列的两种方法。上面的教程现在展示了这种方式。