LoginSignup
6
5

More than 5 years have passed since last update.

[AWS] DynamoDBでシーケンス用テーブルを作る (Node.js)

Last updated at Posted at 2017-06-30

DynamoDBはシーケンス発行の仕組みを持っていませんが、アトミックカウンターの使ってインクリメントすることができます。

シーケンス用テーブル作成

まずはシーケンス用のテーブルを作成します。
ここでは「sequences」という名前にします。
プライマリキーは「name」で文字列です。



スクリーンショット 2017-06-30 10.57.37.png

テーブルができたら、項目を作成します。
name:シーケンス発行したいテーブル名
current_number:現在のシーケンス値(最初だから0)を設定



スクリーンショット 2017-06-30 11.03.17.png

DynamoDBの準備は完了です。

シーケンス発行方法

Node.jsでの例です。
Lambdaで実行することを想定したコードです。

'use strict';

const table = 'test_table';

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

// シーケンス発行関数
function sequence(sequenceName, callback) {
    const params = {
        TableName: "sequences",
        Key: {
            name: sequenceName
        },
        UpdateExpression: "set current_number = current_number + :val",
        ExpressionAttributeValues: {
            ":val":1
        },
        ReturnValues: "UPDATED_NEW"
    };

    docClient.update(params, function(err, data) {
        let id;
        if (err) {
            console.error('Unable to update item. Error JSON:', JSON.stringify(err, null, 2));
        } else {
            console.log('UpdateItem succeeded:', JSON.stringify(data, null, 2));
            id = data.Attributes.current_number;
        }
        callback(id);
    });
}

exports.handler = (event, context, callback) => {

    // シーケンス取得
    sequence(table, function(id) {
        console.log("sequence:" + id);
    });
};

参考にした記事:
DynamoDB でシーケンスを管理する
公式:
ステップ 3.4: アトミックカウンターを増分する

6
5
1

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