如果DynamoDB尚不存在属性,如何将地图作为属性值插入?

时间:2017-09-20 16:36:58

标签: java amazon-web-services amazon-dynamodb

有人可以告诉我如何将地图设置为尚不存在的属性的值。我一直在尝试更新表达式"SET MyAttr.#key = :val",但这仅在属性存在且属性值已经是地图时才有效。

我尝试使用"ADD MyAttr.#key = :val",但后来我得到了:

  

无效的UpdateExpression:语法错误;令牌:“=”,附近:“#key =:val”

我正在使用Java。请注意,我正在尝试使用UpdateItem请求来执行此操作。我突然意识到这可能不适用于地图。我只是假设它会因为我总是能够使用更新请求创建一个新项目和/或属性(如果尚未存在)(使用其他属性值数据类型,如字符串,数字等)。

1 个答案:

答案 0 :(得分:2)

假设我们的DynamoDB表中有以下项目:

{
  "id": "91c2b60d-c428-403c-be42-8657b4f20669",
  "firstName": "John",
  "lastName": "Doe"
}

我们想要在Map中添加自定义属性:

Map<String, String> customAttributes = new HashMap<>();
customAttributes.put("age", "21");
customAttributes.put("gender", "Male");

AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamodb = new DynamoDB(client);

Table table = dynamodb.getTable("users");
UpdateItemSpec updateItemSpec = new UpdateItemSpec()
          .withPrimaryKey("id", "91c2b60d-c428-403c-be42-8657b4f20669")
          .withUpdateExpression("set #customAttributes = :customAttributes")
          .withNameMap(new NameMap().with("#customAttributes", "customAttributes"))
          .withValueMap(new ValueMap().withMap(":customAttributes", customAttributes))
          .withReturnValues(ReturnValue.ALL_NEW);

UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
System.out.println(outcome.getItem().toJSONPretty());

结果:

{
  "id" : "91c2b60d-c428-403c-be42-8657b4f20669",
  "firstName" : "John",
  "lastName" : "Doe",
  "customAttributes" : {
    "gender" : "Male",
    "age" : "21"
  }

}

现在,如果我们要向customAttributes地图添加新属性:

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
    .withPrimaryKey("id", "91c2b60d-c428-403c-be42-8657b4f20669")
    .withUpdateExpression("set customAttributes.#occupation = :value")
    .withNameMap(new NameMap().with("#occupation", "occupation"))
    .withValueMap(new ValueMap().withString(":value", "Programmer"))
    .withReturnValues(ReturnValue.ALL_NEW);

UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

System.out.println(outcome.getItem().toJSONPretty());

我建议你看一下:DynamoDBMapper,它会为你节省大量的代码。