A sort key helps organize and find related data quickly within the same group in a DynamoDB table.
0
0
Sort key purpose and usage in DynamoDB
Introduction
You want to store multiple items that share a common identifier but differ in some detail.
You need to retrieve items in a specific order, like recent orders by date.
You want to filter or query items efficiently within a group.
You want to model one-to-many relationships, like a user and their posts.
You want to avoid scanning the whole table by narrowing down your search.
Syntax
DynamoDB
CreateTable {
TableName: string,
KeySchema: [
{ AttributeName: string, KeyType: 'HASH' }, // Partition key
{ AttributeName: string, KeyType: 'RANGE' } // Sort key
],
AttributeDefinitions: [
{ AttributeName: string, AttributeType: 'S' | 'N' | 'B' }
],
ProvisionedThroughput: {
ReadCapacityUnits: number,
WriteCapacityUnits: number
}
}The partition key groups items, and the sort key orders items within that group.
Sort key is optional but useful for organizing related data.
Examples
This example uses 'UserID' as the partition key and 'Timestamp' as the sort key to store user events in order.
DynamoDB
KeySchema: [
{ AttributeName: 'UserID', KeyType: 'HASH' },
{ AttributeName: 'Timestamp', KeyType: 'RANGE' }
]This example uses only a partition key without a sort key, so each item must have a unique 'OrderID'.
DynamoDB
KeySchema: [
{ AttributeName: 'OrderID', KeyType: 'HASH' }
]Sample Program
This example creates a table with a partition key 'UserID' and a sort key 'MessageID'. It inserts two messages for the same user and queries them ordered by 'MessageID'.
DynamoDB
CreateTable {
TableName: 'UserMessages',
KeySchema: [
{ AttributeName: 'UserID', KeyType: 'HASH' },
{ AttributeName: 'MessageID', KeyType: 'RANGE' }
],
AttributeDefinitions: [
{ AttributeName: 'UserID', AttributeType: 'S' },
{ AttributeName: 'MessageID', AttributeType: 'S' }
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
}
-- Insert messages for user 'user123'
PutItem {
TableName: 'UserMessages',
Item: { UserID: 'user123', MessageID: 'msg001', Content: 'Hello!' }
}
PutItem {
TableName: 'UserMessages',
Item: { UserID: 'user123', MessageID: 'msg002', Content: 'How are you?' }
}
-- Query messages for 'user123' ordered by MessageID
Query {
TableName: 'UserMessages',
KeyConditionExpression: 'UserID = :uid',
ExpressionAttributeValues: { ':uid': 'user123' }
}OutputSuccess
Important Notes
Sort keys let you store multiple items with the same partition key but different sort keys.
Queries using sort keys are faster than scanning the whole table.
You can use operators like BETWEEN or begins_with on sort keys to filter results.
Summary
The sort key organizes related items within the same partition key group.
It helps retrieve data in order and filter efficiently.
Using a sort key models one-to-many relationships in DynamoDB.