NoSQL · Data models beyond tables
How do secondary indexes work in NoSQL systems?
Short answer
A secondary index maintains an alternate key so you can query by a non-primary attribute. It adds write cost and, in distributed stores, is often eventually consistent and limited in the queries it supports.
The primary key determines the main access path. A secondary index copies selected fields into a new structure keyed by the query attribute. In a distributed system that index may live on different nodes, so a write must update both the table and the index.
Local versus global
- Local index: stored with the base partition, so a query may need to contact every partition
- Global index: partitioned by the indexed attribute, so writes may cross partitions
- Global indexes are usually eventually consistent because the index update is asynchronous
- Some systems support only eventual consistency for secondary index reads
{
"TableName": "Orders",
"GlobalSecondaryIndexes": [
{
"IndexName": "orders_by_status",
"KeySchema": [
{ "AttributeName": "status", "KeyType": "HASH" },
{ "AttributeName": "createdAt", "KeyType": "RANGE" }
],
"Projection": { "ProjectionType": "INCLUDE", "NonKeyAttributes": ["total"] }
}
]
}Design indexes for real query patterns and project only needed attributes. A common mistake is indexing a low-cardinality field such as status, which creates a large, hot index partition. Another is expecting the index to support filters it was not built for.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between a local and a global secondary index?
- 2Why are global secondary indexes often eventually consistent?
- 3How do you avoid a hot secondary index?
- 4What does index projection mean?
Say it in the interview
A secondary index creates an alternate query path by copying selected fields into a new key structure. In a distributed store, that means writes update both the table and the index, and the index may be eventually consistent. I choose between local and global based on whether I want the index colocated with the data or partitioned by the indexed field. I avoid indexing low-cardinality fields, because that creates a large hot index partition, and I project only the attributes the query needs.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live NoSQL mock interview and get scored feedback on depth, clarity and confidence.