LoginSignup
5
0

More than 3 years have passed since last update.

【DynamoDB】トランザクションを効かせて書き込みを行う【.Net】

Last updated at Posted at 2019-05-17

DynamoDBに対してトランザクションを効かせた書き込みをやってみました。

書き込む対象

以下のようなテーブルへの書き込みを想定しています。

  • Mapテーブル
    • ID対状態を保持
    • 重複作成は禁止
  • Logテーブル
    • IDと操作日時と操作内容を保持
    • 1から辿ればMapテーブルを再現できるようにする

サンプルコード

private readonly AmazonDynamoDBClient _client;

await _client.TransactWriteItemsAsync(
    new TransactWriteItemsRequest
    {
        TransactItems =
        {
            // マップテーブルへの書き込み
            new TransactWriteItem
            {
                Put = new Put
                {
                    TableName = "Map",
                    Item = new Dictionary<string, AttributeValue>()
                    {
                        { "Id", new AttributeValue { S = /* ID */ }},
                        { "State", new AttributeValue { S = /* 状態 */ }}
                    },
                    ConditionExpression = "attribute_not_exists(Id)" // 重複時は作成不可
                }
            },
            // ログテーブルへの書き込み
            new TransactWriteItem
            {
                Put = new Put
                {
                    TableName = "Log",
                    Item = new Dictionary<string, AttributeValue>()
                    {
                        {"Id", new AttributeValue {S = /* ID */ }},
                        {"DateTimeStr", new AttributeValue {S = /* 操作日時 */ }},
                        {"Operation", new AttributeValue {S = /* 操作内容 */ }}
                    }
                }
            }
        }
    }
);

感想

.NetでDynamoDBをいじるのはサンプルが見つからなくて結構苦労しますね……。
公式サンプルもインデントがズレているように見えて読みにくいですし、結局コード補完や自力でソース読んで作ってました。

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