What you'll learn
- Sort Keys automatically organize data within a Partition Key.
- Use ScanIndexForward to control ascending or descending order.
- A KeyConditionExpression needs an equality test on the partition key (
Type1 = :type); the sort key can add=,<,<=,>,>=,BETWEEN, orbegins_with(e.g.Attack >= :min).
Section 01
Sort Keys in GSIs
If we set Type1 as the Partition Key and Attack as the Sort Key, DynamoDB automatically keeps our Water-type Pokémon sorted by their Attack power! (Store Attack as a Number: as a String, "105" would sort before "65".) When querying, you can easily fetch the strongest Water Pokémon by reading the items in reverse order.
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-Attack-Index",
KeyConditionExpression: "Type1 = :type",
ExpressionAttributeValues: { ":type": "water" },
ScanIndexForward: false // false means descending order (highest attack first!)
}));Ready · 5 steps · Wick
This animation plays when you scroll to it. Press Play to start it now.
All steps as text
- Your app sends Query to the Type1-Attack-Index index with Type1 = "fire". ScanIndexForward left at its default (true).
- DynamoDB hashes "Fire" to b476151f, which routes the request to partition P3.
- P3 returns Cyndaquil (52), Typhlosion (84), Ho-Oh (130).
- This call consumed 0.5 RCU.
- DynamoDB responds with success: ascending order, so the weakest comes back first.
Practice
Your turn
You want the strongest Fire types first. The GSI
Type1-Attack-Index already sorts by Attack — flip the scan direction so the highest Attack comes back at the top.Add
ScanIndexForward: false to return results in descending Attack order.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.
How do you fetch items in descending order (highest to lowest) using a Query in DynamoDB?
Choose one answer.