0
0
DynamoDBquery~5 mins

Querying GSI in DynamoDB

Choose your learning style9 modes available
Introduction

We use Querying GSI to quickly find items in a DynamoDB table using an alternate key. It helps when you want to search by something other than the main key.

You want to find all orders by a specific customer ID instead of the order ID.
You need to get all products in a category quickly.
You want to list all events happening on a certain date.
You want to filter items by a status or tag that is not the main key.
Syntax
DynamoDB
aws dynamodb query \
  --table-name TableName \
  --index-name GSIName \
  --key-condition-expression "GSIPartitionKey = :value" \
  --expression-attribute-values '{":value":{"S":"YourValue"}}'

The --index-name option tells DynamoDB which GSI to use.

The --key-condition-expression filters items by the GSI partition key.

Examples
Finds all orders for customer with ID 'C123' using the CustomerIndex GSI.
DynamoDB
aws dynamodb query \
  --table-name Orders \
  --index-name CustomerIndex \
  --key-condition-expression "CustomerId = :cid" \
  --expression-attribute-values '{":cid":{"S":"C123"}}'
Finds all products in the 'Books' category using the CategoryIndex GSI.
DynamoDB
aws dynamodb query \
  --table-name Products \
  --index-name CategoryIndex \
  --key-condition-expression "Category = :cat" \
  --expression-attribute-values '{":cat":{"S":"Books"}}'
Sample Program

This query finds all music items where the artist is 'The Beatles' using the ArtistIndex GSI.

DynamoDB
aws dynamodb query \
  --table-name Music \
  --index-name ArtistIndex \
  --key-condition-expression "Artist = :artist" \
  --expression-attribute-values '{":artist":{"S":"The Beatles"}}'
OutputSuccess
Important Notes

Make sure the GSI is created before querying it.

You can only query by the GSI's partition key and optionally its sort key.

Querying a GSI is faster than scanning the whole table.

Summary

Querying a GSI lets you find items using an alternate key.

You specify the GSI name and key condition in the query.

This helps you search data in different ways without scanning the whole table.