0
0
DynamoDBquery~5 mins

GSI key selection strategy in DynamoDB

Choose your learning style9 modes available
Introduction
A GSI key selection strategy helps you choose the best keys for your Global Secondary Index to find data quickly and efficiently.
When you want to search your data in a different way than your main table keys.
When you need to speed up queries that filter or sort by attributes not in the main key.
When you want to organize data to support new app features without changing the main table.
When you want to reduce the amount of data scanned during queries.
When you want to improve read performance for specific access patterns.
Syntax
DynamoDB
Create a GSI with:
  - Partition key (hash key): attribute to group items
  - Sort key (optional): attribute to sort items within a group
Example:
  CREATE GLOBAL SECONDARY INDEX index_name ON table_name (partition_key, sort_key);
The partition key decides how data is grouped in the index.
The sort key helps order data inside each group for faster queries.
Examples
Use when you want to find all items in a category quickly.
DynamoDB
Partition key only:
  PartitionKey = "Category"
Use when you want to find all orders by a user sorted by date.
DynamoDB
Partition key and sort key:
  PartitionKey = "UserId"
  SortKey = "OrderDate"
Use when each item is unique and you want fast single-item lookups.
DynamoDB
Partition key with high cardinality:
  PartitionKey = "TransactionId"
Sample Program
This creates a table Orders with a GSI named UserOrdersIndex. The GSI lets you find all orders by a user sorted by order date.
DynamoDB
CREATE TABLE Orders (
  OrderId STRING PRIMARY KEY,
  UserId STRING,
  OrderDate STRING,
  Category STRING
);

CREATE GLOBAL SECONDARY INDEX UserOrdersIndex ON Orders (
  UserId,
  OrderDate
);
OutputSuccess
Important Notes
Choose a partition key with many different values to spread data evenly.
Avoid using attributes with few unique values as partition keys to prevent hotspots.
Use a sort key to enable sorting and range queries within a partition.
Summary
A good GSI key strategy improves query speed and efficiency.
Partition key groups data; sort key orders data inside groups.
Pick keys based on how you want to search and organize your data.