我将 AWS Java SDK v2 与 UpdateExpression 结合使用,这样我就可以更新项目,而无需从 DynamoDB 检索项目。
我已经成功构建了更新表达式,但现在我不知道如何操作。
DynamoDbEnhancedClient client = DynamoDbEnhancedClient.builder()
.dynamoDbClient(DynamoDbClient.builder().region(Region.EU_WEST_1).build())
.extensions(AutoGeneratedUuidExtension.create())
.build();
DynamoDbTable<MyClass> table = client.table("MyTable", TableSchema.fromBean(MyClass.clazz));
SetAction action = SetAction.builder()
.path("#optIn")
.value("if_not_exists(#optIn,:optInValue)")
.putExpressionValue(":optInValue", fromBool(true))
.build();
UpdateExpression updateExpression = UpdateExpression.builder()
.addAction(action)
.build();
// Now I don't know how to call table.execute(updateExpression, uniqueId);
如果您不想在更新之前将项目读入内存,则应使用低级客户端。
对于EnhancedClient,您必须创建一个自定义扩展来覆盖
WriteModification
扩展:
public final class CustomExtension implements DynamoDbEnhancedClientExtension {
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
return WriteModification.builder()
.updateExpression(createUpdateExpression())
.build();
}
}
private static UpdateExpression createUpdateExpression() {
AttributeValue newValue = AttributeValue.builder().s("A new value").build();
SetAction setAction =
SetAction.builder()
.path("#attr1_ref")
.value(":new_value")
.putExpressionName("#attr1_ref", "attr1")
.putExpressionValue(":new_value", newValue)
.build();
UpdateExpression.builder()
.addAction(setAction)
.build();
}
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.extensions(new CustomExtension()))
.build();