AWS SDK DynamoDB Itemを挿入する方法
環境
AWS SDk
DynamoDB
操作方法
1.aws-sdk をインストールします
aws-sdk をインストールします。
2.AWS.DynamoDB Table作成 createTable
usersテーブル を作成します。
const AWS = require('aws-sdk') AWS.config.loadFromPath('./config.json') const dynamoDB = new AWS.DynamoDB() const params = { TableName: 'users', AttributeDefinitions: [ { AttributeName: 'user_id', AttributeType: 'N' }, // number { AttributeName: 'created_at', AttributeType: 'S' }, // string { AttributeName: 'post_id', AttributeType: 'N' } // number ], KeySchema: [ { AttributeName: 'user_id', KeyType: 'HASH' }, // Partition key { AttributeName: 'created_at', KeyType: 'RANGE' } // Sort key ], LocalSecondaryIndexes: [ { IndexName: 'post_local_index', Projection: { ProjectionType: 'ALL' // 全て }, KeySchema: [ { AttributeName: 'user_id', KeyType: 'HASH' }, { AttributeName: 'post_id', KeyType: 'RANGE' } ] } ], GlobalSecondaryIndexes: [ { IndexName: 'post_global_index', Projection: { ProjectionType: 'ALL' }, KeySchema: [ { AttributeName: 'post_id', KeyType: 'HASH' } ], ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 } } ], ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 } } dynamoDB.createTable(params, (err, data) => { if (err) { console.error('Unable to create table. Error JSON:', JSON.stringify(err, null, 2)) } else { console.log('Created table. Table description JSON:', JSON.stringify(data, null, 2)) } })
3.putで複数のItemを挿入する
const AWS = require('aws-sdk') AWS.config.loadFromPath('./config.json') const documentClient = new AWS.DynamoDB.DocumentClient() items = [ { user_id: 1, post_id: 2, created_at: '1544741483', message: 'a2 }, { user_id: 2, post_id: 9, created_at: '1544745083', message: 'b3' }, { user_id: 3, post_id: 3, created_at: '1544748683', message: 'c4' }, { user_id: 1, post_id: 5, created_at: '1544752281', message: 'd5' }, { user_id: 5, post_id: 3, created_at: '1544755883', message: 'e6' }, ] items.forEach(item => { const params = { TableName: 'users', Item: { 'user_id': item.user_id, 'post_id': item.post_id, 'created_at': item.created_at, 'message': item.message } } documentClient.put(params, (err, data) => { if (err) console.log(err) else console.log(data) }) })
4.getメソッドで単一Item取得する
const AWS = require('aws-sdk') AWS.config.loadFromPath('./config.json') const documentClient = new AWS.DynamoDB.DocumentClient() const params = { TableName: 'users', Key: { 'user_id': 1, 'created_at': '1544752281' } } documentClient.get(params, (err, data) => { if (err) console.log(JSON.stringify(err, null, 2)) else console.log(JSON.stringify(data, null, 2)) })