AWS SDK DynamoDB queryメソッドで条件に一致する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))
  }
})

2.queryメソッドで条件に一致するItem取得

const AWS = require('aws-sdk')
AWS.config.loadFromPath('./config.json')
const documentClient = new AWS.DynamoDB.DocumentClient()

const params = {
  TableName: 'users',
  KeyConditionExpression: 'user_id = :user_id and created_at >= :created_at',
  ExpressionAttributeValues: {
    ':user_id': 1,
    ':created_at': '1544752281'
  }
}
documentClient.query(params, (err, data) => {
  if (err) console.log(JSON.stringify(err, null, 2))
  else console.log(JSON.stringify(data, null, 2))
})

3.scanメソッドで条件に一致するItem取得

const AWS = require('aws-sdk')
AWS.config.loadFromPath('./config.json')
const documentClient = new AWS.DynamoDB.DocumentClient()

const params = {
  TableName: 'users',
  FilterExpression: 'message = :message',
  ExpressionAttributeValues: { ':message': 'studygame' }
}
documentClient.scan(params, (err, data) => {
  if (err) console.log(JSON.stringify(err, null, 2))
  else console.log(JSON.stringify(data, null, 2))
})

 

IT

Posted by arkgame