DynamoDB Query a GSI in Node.js (AWS SDK v3)

Querying a global secondary index is a normal Query plus one parameter: IndexName. The key condition then targets the index's keys, not the table's — here AlbumTitle-index lets us fetch songs by album, an access pattern the base table (Artist + SongTitle) can't serve without a scan.

Code

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

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

const items = [];
let lastEvaluatedKey;

do {
  const response = await client.send(
    new QueryCommand({
      TableName: 'Music',
      IndexName: 'AlbumTitle-index',
      KeyConditionExpression: '#hashKey = :hashKeyValue',
      ExpressionAttributeNames: {
        '#hashKey': 'AlbumTitle'
      },
      ExpressionAttributeValues: {
        ':hashKeyValue': {S: 'Danzon'}
      },
      ExclusiveStartKey: lastEvaluatedKey
    })
  );

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

console.log(`Found ${items.length} songs on the album`);

Explanation

  • IndexName — names the GSI to query (TableName is still required). The KeyConditionExpression uses the index's partition (and optional sort) key — AlbumTitle here — with the same operators as a table query.
  • Eventual consistency only — GSIs replicate from the base table asynchronously. Passing ConsistentRead: true on a GSI query doesn't upgrade it; it fails with a ValidationException. (Local secondary indexes do support strong consistency.)
  • You get projected attributes only — a GSI query returns what the index projects (ALL, KEYS_ONLY, or INCLUDE-listed attributes) and cannot fetch the rest from the base table. Need an unprojected attribute? Follow up with GetItem on the table key, or widen the projection.
  • Keys aren't unique in a GSI — many items can share the same index key, and items missing the index key attribute simply don't appear (that's the sparse-index pattern).
  • Pagination — identical to a table query: at most 1 MB per page, loop LastEvaluatedKeyExclusiveStartKey until it's undefined.

Do it visually

The DynamoDB Expression Builder builds the key condition + name/value maps for index queries and copies the code.

To browse a table's indexes and run GSI queries from a form — paginated grid, copy the generated SDK v3 code — download DynoTable.

References

Last verified 2026-07-13 against the official AWS documentation linked above.

Build this request visually

Compose this operation in the free DynamoDB Query Builder — key condition, filter, index, Limit, sort order, and a pagination loop — and copy it back as a runnable SDK v3, CLI, or boto3 program.

Open the DynamoDB Query Builder

Work with DynamoDB without the Console

DynoTable is a fast desktop client for DynamoDB — browse tables, run SQL-style queries, and edit items locally.