0PricingLogin
AWS Solutions Architect · Lesson

Global Secondary Indexes and Local Secondary Indexes

Add GSIs and LSIs to support alternate query patterns without duplicating tables.

Why Secondary Indexes Exist

DynamoDB's primary key defines the only efficient query path on a table. If you need to query items by a different attribute—say, you want to find all orders for a product ID when the table's partition key is CustomerId—you would have to perform an expensive Scan without a secondary index.

Secondary indexes solve this by maintaining a separate, automatically updated copy of the data structured around a different key. DynamoDB offers two types: Global Secondary Indexes (GSI) and Local Secondary Indexes (LSI), each with different trade-offs.

Global Secondary Index (GSI) Basics

A Global Secondary Index lets you define a completely different partition key (and optionally a sort key) from the base table. The GSI is truly global—it spans all partitions of the base table. You can query a GSI to find items by any attribute that you define as the GSI partition key.

GSIs have their own provisioned throughput (or inherit on-demand mode) independent of the base table. You can create up to 20 GSIs per table and can add or delete GSIs at any time on an existing table.

# Create a table with a GSI on ProductId
aws dynamodb create-table \
  --table-name Orders \
  --attribute-definitions \
    AttributeName=OrderId,AttributeType=S \
    AttributeName=ProductId,AttributeType=S \
    AttributeName=OrderDate,AttributeType=S \
  --key-schema AttributeName=OrderId,KeyType=HASH \
  --global-secondary-indexes '[
    {
      "IndexName": "ProductId-OrderDate-index",
      "KeySchema": [
        {"AttributeName": "ProductId", "KeyType": "HASH"},
        {"AttributeName": "OrderDate", "KeyType": "RANGE"}
      ],
      "Projection": {"ProjectionType": "ALL"},
      "ProvisionedThroughput": {"ReadCapacityUnits": 10, "WriteCapacityUnits": 5}
    }
  ]' \
  --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5

All lessons in this course

  1. Tables, Items, and Primary Keys
  2. Provisioned vs On-Demand Capacity
  3. Global Secondary Indexes and Local Secondary Indexes
  4. DynamoDB Streams and Global Tables
← Back to AWS Solutions Architect