LSI and GSI help you find data in DynamoDB in different ways. They make searching faster and easier.
LSI vs GSI comparison in DynamoDB
Local Secondary Index (LSI):
- Same partition key as the main table
- Different sort key
Global Secondary Index (GSI):
- Different partition key
- Different sort key (optional)LSI shares the same partition key as the main table but allows a different sort key.
GSI can have a completely different partition key and sort key, giving more flexibility.
LSI example: Partition Key: UserID Sort Key: OrderDate LSI Sort Key: ProductCategory
GSI example: Partition Key: ProductCategory Sort Key: Price
This creates a table with a main key of UserID and OrderID. It adds an LSI to sort orders by product category for each user. It also adds a GSI to find products by category and price.
CREATE TABLE Orders (
UserID STRING,
OrderID STRING,
OrderDate STRING,
ProductCategory STRING,
Price NUMBER,
PRIMARY KEY (UserID, OrderID),
LOCAL SECONDARY INDEX LSI_ProductCategory (
SORT KEY (ProductCategory)
),
GLOBAL SECONDARY INDEX GSI_CategoryPrice (
PARTITION KEY (ProductCategory),
SORT KEY (Price)
)
);LSI can only be created when the table is created; you cannot add it later.
GSI can be added anytime after the table is created.
LSI shares the same partition key, so it uses the same storage and throughput limits.
GSI has its own throughput and storage, so it can scale independently.
LSI uses the same partition key but a different sort key to give alternate sorting.
GSI uses different partition and sort keys to allow flexible queries.
Use LSI for alternate sorting within the same partition; use GSI for different query patterns.