DynamoDB Query in Node.js (AWS SDK v3)

Query reads every item that shares one partition key, optionally narrowing by the sort key. In AWS SDK v3 you send a QueryCommand whose KeyConditionExpression names the keys and ExpressionAttributeValues supplies the marshalled values.

Code

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

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

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

  do {
    const response = await client.send(
      new QueryCommand({
        TableName: 'Music',
        KeyConditionExpression: 'Artist = :artist AND begins_with(SongTitle, :prefix)',
        ExpressionAttributeValues: {
          ':artist': {S: artist},
          ':prefix': {S: 'C'}
        },
        // false = descending (newest/highest sort key first)
        ScanIndexForward: true,
        Limit: 100,
        ExclusiveStartKey: lastEvaluatedKey
      })
    );

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

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

querySongsByArtist('Arturo Sandoval');

Explanation

  • KeyConditionExpression — must include an equality on the partition key (Artist = :artist) and may add one sort-key condition (=, <, <=, >, >=, BETWEEN, or begins_with). You cannot Scan-style filter here.
  • ExpressionAttributeValues — the :placeholder → value map, in low-level format ({ S: ... }).
  • ScanIndexForwardtrue (default) returns items in ascending sort-key order; false reverses it.
  • Limit — caps items per page, evaluated before any FilterExpression.
  • Pagination — a single Query returns at most 1 MB. When more remains, LastEvaluatedKey is set; feed it back as ExclusiveStartKey until it's undefined. The loop above collects the full result set.
  • To query a secondary index, add IndexName: "...".

Do it visually

The DynamoDB Expression Builder builds the KeyConditionExpression + ExpressionAttributeValues for you and copies the code — no hand-typed placeholders.

To run queries against real tables in a GUI — key-condition form, paginated results grid, copy the generated SDK v3 code — download DynoTable.

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

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