What you'll learn
- 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 (a Query on the index returns only projected attributes). Items missing the index key are left out, which makes the index sparse.
Section 01
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.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({ region: "ap-south-1" });
const docClient = DynamoDBDocumentClient.from(client);
await docClient.send(new QueryCommand({
TableName: "JohtoPokemon",
IndexName: "Type1-Index",
KeyConditionExpression: "Type1 = :type",
ExpressionAttributeValues: { ":type": "water" }
}));Ready · 7 steps · Bloop
This animation plays when you scroll to it. Press Play to start it now.
All steps as text
- Your app sends Scan to the JohtoPokemon table. FilterExpression Type1 = :type, no index.
- P0 reads 25 items to return 1: Totodile.
- P1 reads 25 items to return 1: Feraligatr.
- P2 reads 25 items to return 0.
- P3 reads 25 items to return 1: Quagsire.
- This call consumed 2.5 RCU.
- DynamoDB responds with success: 100 items read and paid for to return 3.
Practice
Your turn
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".Add
IndexName, KeyConditionExpression and ExpressionAttributeValues to query the GSI for "water".Tab inserts two spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the code.
Ctrl/⌘ Enter to run · simulated, no AWS callsSimulated — no AWS calls
Check
Check your understanding
Quick Quiz · one question, as many tries as you need.
Why use a Global Secondary Index instead of a Scan to find all Water-type Pokémon?
Choose one answer.