Secondary Indexes

DynamoDB normally queries only by the partition key.
Secondary indexes allow fast queries using other attributes.

Analogy: alternate lookup views on the same data.

Summary

Secondary indexes = query flexibility beyond the primary key.


Types

Global Secondary Index (GSI)

  • Different partition key from base table
  • Optional different sort key
  • Stored on separate physical partitions
  • Eventually consistent
  • Has own read/write capacity

Analogy: a separate phonebook sorted by email.

Important

A GSI behaves like a separate table.


Local Secondary Index (LSI)

  • Same partition key, different sort key
  • Stored with the same partition
  • Supports strongly consistent reads
  • Shares table capacity

Analogy: another sorting tab in the same folder.

Important

LSI queries stay within one partition key.

Use GSI

  • Query by non-key attribute
  • Query across partitions

Example

Chat App:
Base → chat_id
GSI → user_id
Query: all messages by a user

Use LSI

  • Same partition key
  • Need alternate sorting or range queries

Example

Chat app:
Same chat_id
LSI sort key → num_attachments


Quick Comparison

FeatureGSILSI
Partition Keydifferentsame
Storageseparatesame partition
Consistencyeventualstrong + eventual
Capacityseparateshared
Max per table205