DynamoDB DataMapper For JavaScript でインデックス付きテーブルを作成するには
Amazon DynamoDB DataMapper For JavaScript という TypeScript にも標準対応している DynamoDB の JavaScript 向けデータマッパーライブラリがあります。 このライブラリはテーブル作成・削除の機能もあるので、テスト用テーブル作成もこちらを使ってスクリプト化しようと考えました。 ただドキュメントが少なく、グローバルセカンダリインデックスを付与する方法を探すのに手間取ったため、ここにメモしておきます。 スキーマ定義とテーブル作成 プライマリキー(通常のHASHキー)は user_id です。 外部キー(GSIのHASHキー)は email です。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import { attribute, hashKey, table } from '@aws/dynamodb-data-mapper-annotations' @table('users') class User { @hashKey({ attributeName: 'user_id' }) userId!: string @attribute({ indexKeyConfigurations: { 'emailIndex': 'HASH' } }) email!: string } async function createTable() { await mapper.ensureTableExists(User, { readCapacityUnits: 1, writeCapacityUnits: 1, indexOptions: { 'emailIndex': { type: 'global', projection: 'keys', readCapacityUnits: 1, writeCapacityUnits: 1, } } }) } createTable() .then(() => { console.info('Created DynamoDB table users') }) .catch(err => { console.error(err) }) 結果確認 $ aws dynamodb describe-table --table-name users --endpoint-url http://localhost:4569 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 { "Table": { "TableArn": "arn:aws:dynamodb:us-east-1:000000000000:table/users", "AttributeDefinitions": [ { "AttributeName": "user_id", "AttributeType": "S" }, { "AttributeName": "email", "AttributeType": "S" } ], "GlobalSecondaryIndexes": [ { "IndexSizeBytes": 0, "IndexName": "emailIndex", "Projection": { "ProjectionType": "KEYS_ONLY" }, "ProvisionedThroughput": { "WriteCapacityUnits": 1, "ReadCapacityUnits": 1 }, "IndexStatus": "ACTIVE", "KeySchema": [ { "KeyType": "HASH", "AttributeName": "email" } ], "IndexArn": "arn:aws:dynamodb:ddblocal:000000000000:table/users/index/emailIndex", "ItemCount": 0 } ], "ProvisionedThroughput": { "NumberOfDecreasesToday": 0, "WriteCapacityUnits": 1, "LastIncreaseDateTime": 0.0, "ReadCapacityUnits": 1, "LastDecreaseDateTime": 0.0 }, "TableSizeBytes": 0, "TableName": "users", "TableStatus": "ACTIVE", "KeySchema": [ { "KeyType": "HASH", "AttributeName": "user_id" } ], "ItemCount": 0, "CreationDateTime": 1560437300.665 } }