AWS SDK DynamoDB scanメソッドで全Itemを取得する

環境
AWS SDk
DynamoDB

概要
Query Scan の結果セットにはデータ制限( 1MB )があるので、注意が必要です。
全件取得したつもりが、データ制限により 1MB 分のitemしか取得されていなかったという
意図しない動作が発生しうります。
データ制限を越えると、クエリ応答 に LastEvaluatedKey がセットされます。
以下実装では、LastEvaluatedKey が設定されている間、繰り返しscanをして
全item取得しています。

操作方法
1.aws-sdk をインストールします
aws-sdk をインストールします。

2.AWS.DynamoDB Table作成 createTable
usersテーブル を作成します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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))
}
})
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)) } })
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.scanメソッドで全Item取得する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const AWS = require('aws-sdk')
AWS.config.loadFromPath('./config.json')
const documentClient = new AWS.DynamoDB.DocumentClient()
const scanAll = async () => {
let params = {
TableName: 'users',
}
let items = []
const scan = async () => {
console.log('execute scan 12345')
console.log(params)
const result = await documentClient.scan(params).promise()
items.push(...result.Items)
if (result.LastEvaluatedKey) {
params.ExclusiveStartKey = result.LastEvaluatedKey
await scan()
}
}
try {
await scan()
return items
} catch (err) {
console.error(`[Error]: ${JSON.stringify(err)}`)
return err
}
}
(async () => {
const items = await scanAll()
})()
const AWS = require('aws-sdk') AWS.config.loadFromPath('./config.json') const documentClient = new AWS.DynamoDB.DocumentClient() const scanAll = async () => { let params = { TableName: 'users', } let items = [] const scan = async () => { console.log('execute scan 12345') console.log(params) const result = await documentClient.scan(params).promise() items.push(...result.Items) if (result.LastEvaluatedKey) { params.ExclusiveStartKey = result.LastEvaluatedKey await scan() } } try { await scan() return items } catch (err) { console.error(`[Error]: ${JSON.stringify(err)}`) return err } } (async () => { const items = await scanAll() })()
const AWS = require('aws-sdk')
AWS.config.loadFromPath('./config.json')
const documentClient = new AWS.DynamoDB.DocumentClient()

const scanAll = async () => {
  let params = {
    TableName: 'users',
  }
  let items = []

  const scan = async () => {
    console.log('execute scan 12345')
    console.log(params)
    const result = await documentClient.scan(params).promise()
    items.push(...result.Items)

    if (result.LastEvaluatedKey) {
      params.ExclusiveStartKey = result.LastEvaluatedKey
      await scan()
    }
  }

  try {
    await scan()
    return items
  } catch (err) {
    console.error(`[Error]: ${JSON.stringify(err)}`)
    return err
  }
}

(async () => {
  const items = await scanAll()
})()

 

IT

Posted by arkgame