Lea*_*ner 4 amazon-web-services amazon-dynamodb
我们有一个 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);
}
Run Code Online (Sandbox Code Playgroud)
更新特定列时,需要指定要更新的列。假设我们有这个表:
现在假设我们要更新存档列。您需要在代码中指定列。在这里,我们将与键对应的项目的存档列更改为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";
Run Code Online (Sandbox Code Playgroud)
注意:这不是增强型客户端。
此代码来自 AWS 教程,该教程展示了如何使用 Spring Boot 构建 Java Web 应用程序。完整教程在这里:
要使用增强客户端更新单个列,请调用Table 方法。这将返回一个DynamoDbTable 实例。现在您可以调用updateItem方法。
这是使用增强客户端更新存档列的逻辑。注意你得到一个Work对象,调用它的setArchive然后传递Work对象。workTable.updateItem(r->r.item(work));
爪哇代码:
// 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 "";
}
Run Code Online (Sandbox Code Playgroud)
此答案显示了更新 DynamoDB 表中单个列的两种方法。上面的教程现在显示了这种方式。
| 归档时间: |
|
| 查看次数: |
856 次 |
| 最近记录: |