Lesson 3 of 10 Amazon DynamoDB

Querying on Other Attributes with Local and Global Secondary Indexes

This lesson explains how secondary indexes let a table answer queries on attributes outside its primary key, without scanning. Choosing between a local and a global secondary index is a frequent exam question.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish local and global secondary indexes by key, consistency, capacity and when they can be created.
  • Choose a projection type that balances storage and write cost against the queries an index must answer.
  • Explain how sparse indexes work and how a throttled global secondary index affects the base table.

Local and global secondary indexes

A table can be queried efficiently only by its primary key. A secondary index stores a copy of the table's data organised by a different key, so the same items can be queried another way, for example orders by status instead of by customer. DynamoDB maintains indexes automatically when items are written. There are two kinds, and they differ in flexibility and consistency.

A local secondary index (LSI) keeps the table's partition key and uses a different sort key, so it offers another ordering within each item collection, such as a customer's orders sorted by total rather than by date. It must be defined when the table is created, uses the table's capacity, and supports strongly consistent reads. Because an LSI is stored with the table's partitions, all items with the same partition key, in the table and its LSIs together, are limited to 10 GB.

A global secondary index (GSI) can use any attributes as its partition and sort keys, so it supports entirely new access patterns, such as finding all orders with a given status across all customers. A GSI can be added or deleted at any time and has its own capacity. DynamoDB updates it asynchronously, so reads are eventually consistent only. If a provisioned GSI has too little write capacity, writes to the base table are throttled. Items that lack the index's key attributes are not copied into it, which produces a sparse index that contains only the items of interest.

The following table summarises the differences.

Local secondary index (LSI)
KeysSame partition key, different sort key
When createdOnly with the table
CapacityShares the table's
Read consistencyStrong or eventual
Limit per table5
Size limit10 GB per partition key value (item collection)
Global secondary index (GSI)
KeysAny partition key and optional sort key
When createdAt any time
CapacityIts own
Read consistencyEventual only
Limit per table20 (default quota)
Size limitNone

The following diagram compares the keys and behaviour of the base table and its two kinds of index.

A table keyed by customerId and orderDate, a local secondary index that keeps customerId and sorts by total, and a global secondary index keyed by status. The LSI is created with the table, shares its capacity, supports strongly consistent reads and limits each item collection to 10 GB. The GSI can be added at any time and has its own capacity, but is updated asynchronously, so its reads are eventually consistent.
An LSI offers another sort order within the same item collection; a GSI supports a new access pattern across the whole table.
Sort into groups

LSI or GSI?

Exam skills 1.3.4

Tell local and global secondary indexes apart by what they allow.

Log in to try this activity Interactive activities are free with an account.

Projections

Each index stores a copy of selected attributes, and its projection type decides which ones. The choice balances the cost of storing and writing the copy against the queries the index can answer on its own.

KEYS_ONLY stores only the table's primary key and the index keys. It is the smallest and cheapest to maintain, but a query that needs other attributes must read each item again from the table. INCLUDE adds named attributes, such as the order total and status that a list screen displays, so the common query is answered from the index alone. ALL copies every attribute, which answers any query but stores and writes each item twice. Every write to the table that changes a projected attribute also consumes write capacity on the index, so projecting more attributes increases write cost as well as storage. The following table summarises the three types.

ProjectionStoresTrade-off
KEYS_ONLYThe table and index keysSmallest and cheapest; other attributes need a second read from the table
INCLUDEKeys plus named attributesBalances cost against the queries it can answer alone
ALLEvery attributeAnswers any query, but doubles storage and write cost

A GSI query cannot fetch attributes that were not projected; an LSI can, at the cost of extra reads from the table.

Sparse indexes and throttling

Secondary indexes have particular characteristics that affect their contents and the throughput of the base table.

  • Sparse index: only items that have the index key attribute appear in the index, an efficient way to index a subset such as open orders. Removing the attribute when an order closes removes it from the index.
  • GSI write capacity: every table write that changes an indexed attribute also writes to the GSI. If a GSI on a provisioned table lacks write capacity, writes to the base table are throttled too.
  • Backfilling: adding a GSI to a large table reads the whole table to build the index; the index is usable once its status is ACTIVE.
Scenario questions

Projections and sparse indexes

Exam skills 1.3.4 · 4.3.2

Choose what an index stores, and which items appear in it.

Log in to try this activity Interactive activities are free with an account.

Adding a GSI

Example. Add an index for querying orders by status, newest first. New attributes used as index keys must be declared in the attribute definitions.

aws dynamodb update-table --table-name Orders \
  --attribute-definitions AttributeName=status,AttributeType=S AttributeName=createdAt,AttributeType=S \
  --global-secondary-index-updates '[{"Create":{"IndexName":"status-index",
    "KeySchema":[{"AttributeName":"status","KeyType":"HASH"},{"AttributeName":"createdAt","KeyType":"RANGE"}],
    "Projection":{"ProjectionType":"INCLUDE","NonKeyAttributes":["total"]}}}]'

aws dynamodb query --table-name Orders --index-name status-index \
  --key-condition-expression "#s = :s" --expression-attribute-names '{"#s":"status"}' \
  --expression-attribute-values '{":s":{"S":"PENDING"}}' --no-scan-index-forward
Worked example

Choosing between an LSI and a GSI

A table of support tickets has partition key customerId and sort key ticketId. Two new access patterns arrive:

Access patternIndexReason
A customer's tickets sorted by last updateLSI with sort key updatedAtSame partition key, different sort; must be created with the table
All open tickets for an agent, across customersGSI with partition key agentId, sort key statusDifferent partition key; can be added at any time

The table already exists, so an LSI is no longer possible; the developer adds a GSI keyed on customerId and updatedAt instead. GSIs are eventually consistent and have their own capacity: if a GSI on a provisioned table is under-provisioned, writes to the base table are throttled, a frequently tested trap.

Check yourself

An existing table needs a new query by email address, using a different partition key. Which kind of index can be added?

Show answer

A global secondary index. A local secondary index must use the table's partition key and can only be created with the table.

Exam Tips

Remember for the exam

  • To query by an attribute outside the key, add a GSI rather than scanning the table.
  • Strongly consistent reads on an alternate sort key require an LSI, which must be created with the table.
  • A new query pattern on an existing table needs a GSI, because an LSI cannot be added later.
  • To index only a subset of items, use a sparse GSI.
  • An under-provisioned GSI throttles writes to its base table.