The Johto Pokedex (GSIs)
Welcome to the Johto Region! Now that you've mastered the basics of DynamoDB in Kanto, it's time to learn the advanced patterns that make DynamoDB truly powerful.
In Kanto, we learned that DynamoDB items are stored based on their Partition Key. But what if you need to look up a Pokémon by its Type1 instead of its Name? A Global Secondary Index (GSI) is like a secondary Pokédex. It automatically copies data from your main table but uses a different attribute as the Partition Key.
Key takeaways
- GSIs allow querying on non-primary key attributes.
- Data is asynchronously replicated from the base table to the index.
- Every GSI adds storage and write cost; project only attributes the access pattern needs.
Creating a GSI
You create an index on the table and choose a new Partition Key (and optionally a new Sort Key). For our Johto Pokédex, we want to find all Water type Pokémon quickly, so we use Type1 as the Partition Key for the GSI. GSI reads are eventually consistent, and a low-cardinality value such as Type1 can become hot at large scale. Treat this as a teaching model, then validate real traffic distribution before production.
Interactive Challenge
The Pokédex is keyed by Name, but we want every Water type without a slow full-table Scan. Point the Query at the Type1-Index GSI and match Type1 = :type where :type is "water".
IndexName, KeyConditionExpression and ExpressionAttributeValues to query the GSI for "water".Quick Quiz
Why use a Global Secondary Index instead of a Scan to find all Water-type Pokémon?
Make your choice to test your understanding. Submit to check, and if it's not quite right you can adjust and try again.