DynamoDB Query a GSI in Python (boto3)

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 boto3

client = boto3.client("dynamodb")

paginator = client.get_paginator("query")

items = []
for page in paginator.paginate(
    TableName="Music",
    IndexName="AlbumTitle-index",
    KeyConditionExpression="#hashKey = :hashKeyValue",
    ExpressionAttributeNames={"#hashKey": "AlbumTitle"},
    ExpressionAttributeValues={":hashKeyValue": {"S": "Danzon"}},
):
    items.extend(page["Items"])

print(f"Found {len(items)} 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 raises 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 get_item 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).
  • Paginationclient.get_paginator("query") follows LastEvaluatedKey across pages exactly as on a table query; each page carries an Items list.
  • On the resource API, the same query is table.query(IndexName="AlbumTitle-index", KeyConditionExpression=Key("AlbumTitle").eq("Danzon")) with native Python values.

Do it visually

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

To browse a table's indexes and run GSI queries from a form — paginated grid, copy-as-code — download DynoTable.

References

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

Costruisci questa richiesta visivamente

Componi questa operazione nel Generatore di query DynamoDB gratuito — condizione di chiave, filtro, indice, Limit, ordine di ordinamento e un loop di paginazione — e copiala come programma eseguibile per SDK v3, CLI o boto3.

Apri il Generatore di query DynamoDB

Lavora con DynamoDB senza la Console

DynoTable è un client desktop veloce per DynamoDB — sfoglia le tabelle, esegui query in stile SQL e modifica gli Item localmente.