DynamoDB Scan in Node.js (AWS SDK v3)

Scan reads every item in a table or index, page by page, then optionally drops rows with a FilterExpression. In AWS SDK v3 you send a ScanCommand and loop on LastEvaluatedKey until the whole table is read.

Code

import {DynamoDBClient, ScanCommand} from '@aws-sdk/client-dynamodb';

const client = new DynamoDBClient({region: 'us-east-1'});

async function scanRecentSongs() {
  const items = [];
  let lastEvaluatedKey;

  do {
    const response = await client.send(
      new ScanCommand({
        TableName: 'Music',
        FilterExpression: '#yr >= :year',
        ExpressionAttributeNames: {'#yr': 'Year'},
        ExpressionAttributeValues: {':year': {N: '2010'}},
        ExclusiveStartKey: lastEvaluatedKey
      })
    );

    items.push(...(response.Items ?? []));
    lastEvaluatedKey = response.LastEvaluatedKey;
  } while (lastEvaluatedKey);

  console.log(`Matched ${items.length} songs`);
  return items;
}

scanRecentSongs();

Explanation

  • FilterExpression — applied after the read, on the server. It shrinks the response but not the cost: you pay to read every item scanned, filtered or not.
  • ExpressionAttributeNamesYear is a reserved word, so it's aliased to #yr.
  • Pagination — each Scan page reads at most 1 MB before filtering, so a filtered page can come back empty while still setting LastEvaluatedKey. You must keep looping until it's undefined, or you'll silently miss matches.
  • Limit — caps items scanned per page (pre-filter), not items returned.
  • For a large full-table scan, split the work across workers with Segment / TotalSegments (a parallel scan).
  • Prefer Query. Scan reads the whole table; on anything but a tiny table it's slow and expensive.

Do it visually

Assembling a filter by hand? The DynamoDB Expression Builder builds the FilterExpression + name/value maps and copies runnable code.

To explore tables in a GUI — with filtered, paginated result grids and copy-as-code — download DynoTable, instead of scanning blind from a script.

不必透過主控台就能操作 DynamoDB

DynoTable 是一款快速的 DynamoDB 桌面用戶端 — 瀏覽表格、執行 SQL 風格的查詢,並在本機編輯項目。