我们有一个 DynamoDB 表,它有一个属性计数器,它将基于一个事件由多个 lambda 异步递减。我正在尝试使用 UpdateItemEnhancedRequest(使用 Dynamodb 增强型客户端。 - JAVA SDK 2)更新计数器。我能够建立更新计数器的条件,但它更新整个项目而不仅仅是计数器。有人可以指导如何使用 DynamoDb Enhanced Client 更新单个属性吗?
代码示例
public void update(String counter, T item) {
AttributeValue value = AttributeValue.builder().n(counter).build();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":value", value);
Expression myExpression = Expression.builder()
.expression("nqctr = :value")
.expressionValues(expressionValues)
.build();
UpdateItemEnhancedRequest<T> updateItemEnhancedRequest =
UpdateItemEnhancedRequest.builder(collectionClassName)
.item(item)
.conditionExpression(myExpression)
.build();
getTable().updateItem(updateItemEnhancedRequest);
}
最佳答案
更新特定列时,需要指定要更新的列。假设我们有这个表:
现在假设我们要更新 存档 列。您需要在代码中指定列。这里我们将键对应的项目的 存档 列更改为 关闭 (单列更新)。请注意,我们使用名为 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 方法。
这是使用增强客户端更新 存档 列的逻辑。注意你得到了一个 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 表中单个列的两种方法。上面的教程现在显示了这种方式。
关于amazon-web-services - 使用 UpdateItemEnhancedRequest DynamoDb java sdk2 更新特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66010749/