← Lessons

quiz vs the machine

Gold1410

Databases

Secondary Indexes in NoSQL

Secondary indexes add new ways to query data beyond the primary key, but each one has costs to weigh.

5 min read · core · beat Gold to climb

Querying Beyond the Primary Key

A NoSQL store routes reads through the primary key. To answer a query that filters on a different attribute, you need a secondary index, a separate structure that maps another attribute to the items that have it.

Two Common Flavors

  • A local secondary index shares the same partition key but offers a different sort key, giving new ordering within a partition.
  • A global secondary index uses an entirely different partition key, letting you query the data by a completely new dimension.

How It Works

The store maintains the index automatically. When you write an item, the index entry is updated so that a query on the indexed attribute can find the item quickly without scanning everything.

What It Costs

  • Indexes consume extra storage because the indexed attributes are copied.
  • Every write must also update the index, adding write cost.
  • A global secondary index is often eventually consistent, so a fresh write may not appear in it immediately.

When to Add One

Add a secondary index when a real access pattern needs it, not speculatively. Each index earns its keep only if a query truly depends on it.

Key idea

Secondary indexes let you query NoSQL data by attributes other than the primary key, at the cost of extra storage, write overhead, and sometimes eventual consistency.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a global secondary index let you do?

2. What is a cost of maintaining a secondary index?