We use composite sort keys to organize related data together in a single table. This helps us find and sort items easily by combining multiple pieces of information into one key.
0
0
Composite sort key pattern in DynamoDB
Introduction
You want to store different types of related data in one table and retrieve them together.
You need to sort items by more than one attribute, like date and category.
You want to quickly find all items related to a user, but also sort them by type or time.
You want to group orders by customer and then sort by order date.
You want to store events with both event type and timestamp in one key for easy queries.
Syntax
DynamoDB
PartitionKey: string
SortKey: string (usually combines multiple values separated by a delimiter, e.g., '#')The sort key is a single string that combines multiple pieces of information.
Use a clear delimiter like '#' to separate parts inside the sort key.
Examples
This example stores an order for user 123 with the order date in the sort key.
DynamoDB
PK = "USER#123" SK = "ORDER#2024-06-01"
This example stores a review for product 456 with the review date in the sort key.
DynamoDB
PK = "PRODUCT#456" SK = "REVIEW#2024-05-30"
This example stores profile information for user 123 using a composite sort key.
DynamoDB
PK = "USER#123" SK = "PROFILE#INFO"
Sample Program
This example creates a table with a composite sort key pattern. It inserts three orders for the same user with dates in the sort key. Then it queries all orders for that user, sorted by the order date.
DynamoDB
CREATE TABLE Orders ( PK STRING, SK STRING, OrderAmount NUMBER, PRIMARY KEY (PK, SK) ); -- Insert orders for user 123 INSERT INTO Orders (PK, SK, OrderAmount) VALUES ('USER#123', 'ORDER#2024-06-01', 100); INSERT INTO Orders (PK, SK, OrderAmount) VALUES ('USER#123', 'ORDER#2024-06-15', 150); INSERT INTO Orders (PK, SK, OrderAmount) VALUES ('USER#123', 'ORDER#2024-07-01', 200); -- Query all orders for user 123 sorted by date SELECT * FROM Orders WHERE PK = 'USER#123' ORDER BY SK;
OutputSuccess
Important Notes
Always choose a delimiter that won't appear in your data to avoid confusion.
Composite sort keys let you store and query different item types under the same partition key.
Summary
Composite sort keys combine multiple values into one string to organize data.
This pattern helps group and sort related items efficiently.
Use clear delimiters to separate parts inside the sort key.