DynamoDBから特定のテーブルの全項目データを取得する(TypeScript/Node.js)

AWS SDKのDynamoDB.DocumentClientscanメソッドを用いるのですが、そのままではテーブルのサイズが大きい場合に一部のデータしか取得できません。

バッチ処理などで、テーブル内の全項目を取得したいシーンもあると思います。(頻繁にそういった操作が必要になるのなら、アプリケーションの設計ミスのような気がしますが...)

そういった際はLastEvaluatedKeyを用いれば簡単に実現可能です。以下のコードはTypeScriptですが、JavaScriptの場合もほぼ同じです(型定義を消せばいいだけ)。

import awsSdk from 'aws-sdk';
import { DocumentClient } from 'aws-sdk/lib/dynamodb/document_client';

const documentClient = new awsSdk.DynamoDB.DocumentClient({
  region: 'ap-northeast-1',
});

const scanAll = async (params: DocumentClient.ScanInput) => {
  const items: DocumentClient.AttributeMap[] = [];

  let lastEvaluatedKey: undefined | DocumentClient.Key;

  while (true) {
    const res = await documentClient.scan({
      ...params,
      ExclusiveStartKey: lastEvaluatedKey,
    }).promise();

    if (res.Items) {
      res.Items.forEach(item => items.push(item));
    }

    if (!res.LastEvaluatedKey) {
      break;
    }

    lastEvaluatedKey = res.LastEvaluatedKey;
  }

  return items;
};

以下のように用いることができます。

scanAll({ TableName: 'テーブル名' })
  .then((items) => {
    // ...
  });