8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【DynamoDB】LastEvaluatedKeyを使ってscanリクエストで全件取得

Posted at

はじめに

RDBMSを使っていると、allとかで全件取得出来て特に気にする必要がないのですが、DynamoDBでは1MBまでのデータ量の件数のみしか取得が出来ないので、知っていないとあれ全件取得出来ていない...みたいなことになり私のように痛い目にあってしまうので、自分への戒めの意味も込めて残しておきます。

情報ソース:DynamoDB でのスキャンの使用

環境

  • Nodejs

実装

const AWS = require('aws-sdk');
const DynamoDB = new AWS.DynamoDB.DocumentClient({region: "ap-northeast-1"});
const tableName = 'hoges';

module.exports.hello = async (event, context) => {
    try {
        // scan用のパラメーターをセット
        const params = {
            TableName: tableName
        }
        // scanで取得したデータを格納する空の配列を定義しておく
        let items = []

        const scan = async () => {
            const result = await DynamoDB.scan(params).promise()
            items.push(...result.Items)

            // scanリクエストを行なった時にLastEvaluatedKeyがあれば、再帰的にリクエストを繰り返す
            if (result.LastEvaluatedKey){
                params.ExclusiveStartKey = result.LastEvaluatedKey
                await scan()
            }
        }

        await scan()
        const count = items.length
        for (let i = 0; i < count; i++){
            console.log(`id: ${items[i]['id']}`)
        }
        console.log(`Execution result: ${count}`)
    } catch (err) {
        console.error(`[Error]: ${JSON.stringify(err)}`)
        return err
    }
}

8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?