3
0

More than 3 years have passed since last update.

DynamoDB の条件付き書き込みを試してみる - condition-expression

Posted at

デフォルトでは、DynamoDB 書き込みオペレーション (PutItem、UpdateItem、DeleteItem) は無条件です。
つまり、これらの各オペレーションでは、指定されたプライマリキーを持つ既存の項目が上書きされます。

条件付き書き込みを利用すると項目の属性が 1 つ以上の想定条件を満たす場合のみに成功できるようできます。それ以外の場合は、エラーが返されます。

とりあえず検証してみる。


1.適当なtableを作成する

項目を追加する。

item.json
{
    "Id": { "N": "100"},
    "Price": {"N": "3000"},
    "Category": {"S": "Tshirt"}
}
aws dynamodb put-item \
    --table-name fashion \
    --item file://item.json 

2.更新される場合

ここでは、limit 2000 以下のものに対してのみ、update するものとする。

values.json
{
    ":discount": { "N": "600"},
    ":limit": {"N": "2000"}
}
aws dynamodb update-item \
    --table-name fashion \
    --key '{"Id": {"N": "100"}}' \
    --update-expression "SET Price = Price - :discount" \
    --condition-expression "Price > :limit" \
    --expression-attribute-values file://values.json

この場合は、3000 - 600 = 2400 なので更新される。

3.更新されない場合

では、さらに discount 600 にしてみます。

values2.json
{
    ":discount": { "N": "600"},
    ":limit": {"N": "2000"}
}
aws dynamodb update-item \
    --table-name Fashion \
    --key '{"Id": {"N": "100"}}' \
    --update-expression "SET Price = Price - :discount" \
    --condition-expression "Price > :limit" \
    --expression-attribute-values file://values2.json

この場合は、2400 - 600 = 1800 で、limit = 2000 より小さいので更新されない。

3
0
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
0