LoginSignup
3
3

More than 5 years have passed since last update.

DynamoDBのputItemで追加と更新の実現方法

Last updated at Posted at 2017-02-23

まずAWSのドキュメント→開発者ガイド→DynamoDB での項目の操作を見てみましょう。

PutItem

新しい項目を作成します。同じキーを持つ項目がテーブルにすでに存在する場合は、新しい項目に置き換えられます。テーブル名と書き込む項目を指定する必要があります。

UpdateItem

項目が存在しない場合、このオペレーションは新しい項目を作成します。すでに存在する場合は、既存の項目の属性を変更します。テーブル名と変更する項目のキーを指定する必要があります。更新する属性ごとに、新しい値を指定する必要があります。
※UpdateItemの使い方はDynamoDBのupdateItemのValidationException解消方法に参照できます。

AWSマネジメントコンソールでDynamoDBのテーブル作成

スクリーンショット 2017-02-21 18.20.12.png

idはプライマリキーパーティションキーになっています。

  • 下記のデータ(csv1)をputitemします。
id,name
10000,hello_one
10001,hello_two
10002,hello_three
10004,hello_four
  • DynamoDBの結果
id,name
10000,hello_one
10001,hello_two
10002,hello_three
10004,hello_four
  • 下記のデータ(csv2)をputitemします。
id,name
10000,hello_one_two
10001,hello_two_three
10002,hello_three
10004,hello_four
  • DynamoDBの結果
id,name
10000,hello_one
10000,hello_one_two
10001,hello_two
10001,hello_two_three
10002,hello_three
10004,hello_four

結果

id= 10000のものが新しい項目として作成されています。

存在しているidの項目を更新する解決方法

テーブル作成

AWSマネジメントコンソールからではなくて、AWS-CLIでコマンドで作成します。

aws dynamodb create-table --table-name test --attribute-definitions '[{"AttributeName": "id", "AttributeType": "S"}]' --key-schema '[{"AttributeName": "id", "KeyType": "HASH"}]' --provisioned-throughput '{"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}'

idのプライマリキーのタイプはHASHを指定すればid存在したら更新します。

  • もう一回csv1、csv2をputItemでDynamoDBに書き込む場合
  • DynamoDBの結果
id,name
10000,hello_one_two
10001,hello_two_three
10002,hello_three
10004,hello_four

まとめ

テーブル作成する時、プライマリキーのタイプをHASHかHASH+RANGEにしてすれば、putItemでDynamoDBの項目を追加と更新(=updateItem)が両方実現できます。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3