0
0
DynamoDBquery~5 mins

LSI vs GSI comparison in DynamoDB

Choose your learning style9 modes available
Introduction

LSI and GSI help you find data in DynamoDB in different ways. They make searching faster and easier.

You want to search data by a different key than the main one.
You need to sort data differently when searching.
You want to query data quickly without scanning the whole table.
You want to add extra ways to find items without changing the main table.
You want to control how much storage and speed your searches use.
Syntax
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.

Examples
LSI lets you query orders by user and then sort by product category instead of order date.
DynamoDB
LSI example:
Partition Key: UserID
Sort Key: OrderDate
LSI Sort Key: ProductCategory
GSI lets you find all products in a category and sort them by price, independent of the main table keys.
DynamoDB
GSI example:
Partition Key: ProductCategory
Sort Key: Price
Sample Program

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.

DynamoDB
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)
  )
);
OutputSuccess
Important Notes

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.

Summary

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.