DynamoDB Query a GSI with the AWS CLI
Querying a global secondary index is a normal aws dynamodb query plus one flag: --index-name. 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
aws dynamodb query \
--table-name 'Music' \
--index-name 'AlbumTitle-index' \
--key-condition-expression '#hashKey = :hashKeyValue' \
--expression-attribute-names '{"#hashKey":"AlbumTitle"}' \
--expression-attribute-values '{":hashKeyValue":{"S":"Danzon"}}'The output is the matching items in DynamoDB JSON:
{
"Items": [
{"Artist": {"S": "Arturo Sandoval"}, "SongTitle": {"S": "Cubano Chant"}, ...}
],
"Count": 2,
"ScannedCount": 2
}Explanation
--index-name— names the GSI to query (--table-nameis still required). The--key-condition-expressionuses the index's partition (and optional sort) key —AlbumTitlehere — with the same operators as a table query.- Eventual consistency only — GSIs replicate from the base table asynchronously. Adding
--consistent-readto a GSI query doesn't upgrade it; it fails with aValidationException. (Local secondary indexes do support strong consistency.) - You get projected attributes only — a GSI query returns what the index projects (
ALL,KEYS_ONLY, orINCLUDE-listed attributes) and cannot fetch the rest from the base table. - 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 is automatic — the CLI follows the service's pagination tokens behind the scenes and prints the combined result. Use
--max-itemsto cap output (aNextTokenappears; resume with--starting-token), or--no-paginatefor a single service call.
Do it visually
The DynamoDB Expression Builder builds the key condition + name/value maps for index queries and hands you a ready-to-run CLI command.
To browse a table's indexes and run GSI queries from a form — paginated grid, copy-as-CLI — download DynoTable.
Related examples
- DynamoDB Query a GSI in Node.js — the same index query with AWS SDK v3.
- DynamoDB Query a GSI in Python — the same index query with boto3.
- DynamoDB Query with the AWS CLI — querying the base table.
- GSI vs. LSI — which index type fits the access pattern.
- Why GSIs are eventually consistent — the replication lag explained.
- "The table does not have the specified index" — the index name doesn't match (GSI names are case-sensitive).
- "Consistent reads are not supported on global secondary indexes" — why the consistent-read flag fails on a GSI.
References
- Query — Amazon DynamoDB API Reference
- query — AWS CLI Command Reference
- Using Global Secondary Indexes in DynamoDB — Amazon DynamoDB Developer Guide
- Using AWS CLI pagination options — AWS CLI User Guide
Last verified 2026-07-13 against the official AWS documentation linked above.