LoginSignup
3
2

More than 3 years have passed since last update.

DynamoDB で auto increment のような事をする際のメモ

Posted at

DynamoDBでMySQLでのオートインクリメントのような事をするには、
数値カウント用のテーブルを作って、そこで一意の数値を採番し、
採番した数値をオートインクリメントの値として使用する。

  • カウンタの管理用のテーブルを用意 (テーブル名、カラム名はなんでも良い)
    • テーブル名 : AtomicCounter
    • パーティションキー名 : CountNumber
  • カラム名に Counter は使用出来なかった
import boto3

def get_increment_number(counter_key):
    dynamoDB = boto3.resource("dynamodb")
    atom_cnt = dynamoDB.Table("AtomicCounter")
    res = atom_cnt.update_item(
        Key={
            'CounterKey': counter_key
        },
        UpdateExpression='ADD CountNumber :incr',
        ExpressionAttributeValues={
            ':incr': 1
        },
        ReturnValues="UPDATED_NEW"
    )
    return res['Attributes']['CountNumber']
3
2
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
2