のは、私たちがDynamoDBの表に、以下の項目を持っていると仮定しましょう:
{
"id": "91c2b60d-c428-403c-be42-8657b4f20669",
"firstName": "John",
"lastName": "Doe"
}
、我々は、カスタムを追加したいが、我々は地図を持っているという属性:
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マップに新しい属性を追加したい場合は0
は今、:
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、それはあなたのコードの行のトンを保存します。
これは私が尋ねた質問に答えてくれます。しかし、すでに存在する場合、Dynamoがマップに追加するアップデートを実行することは可能ですか?提供したソリューションは、既存のマップを上書きします。または、アイテムを最初に照会してから、アイテム/ attrが現在存在するかどうかに基づいて別の 'UpdateItemSpec'を作成する必要がありますか? – RTF
はい、可能です!私はあなたの例を示すために私の答えを編集します。 –
アップデートいただきありがとうございますが、私が探しているのは、a)のワンショットアップデートです。私のキーと値のペアを持つマップを作成し、アイテムや属性がまだ存在しない場合はマップをmy属性の値として設定するか、またはb)を設定します。属性内の既存のマップを指定されたキーと値のペアで更新します。私はこれは単一の要求では可能ではないと思う:https://stackoverflow.com/questions/35377729/how-to-set-a-dynamodb-map-property-value-when-the-map-doesnt-exist-まだ?rq = 1 – RTF