Database Systems · UGC NET: NoSQL
NoSQL Indexing Ordering and Query Optimization
Overview
NoSQL systems drop the fixed relational schema, but they still must answer queries quickly, so they depend on index structures and on a query planner that chooses an access path.
This lesson covers how indexes are organised (B-tree, LSM-tree, compound, multikey, sparse, TTL, hashed), how key ordering in MongoDB, Cassandra, HBase, Redis and DynamoDB decides which queries are cheap, and how an optimizer converts a query into a plan using heuristic rules and cost estimates.
It belongs to the NoSQL part of the DBMS extras area and assumes you already know relational algebra (selection, projection, join), basic file organisation (blocks, blocking factor, dense and sparse indexes), and the idea of a cost model measured in block transfers.
The topic is examined through "which index can this query use", "is the sort served by the index", and "which plan is cheaper", so precision about definitions matters more than memorising products.
Key concepts
- Query optimisation: selecting, among logically equivalent plans, the one with the least estimated cost. Two families exist: heuristic (rule-based) optimisation (RBO) and cost-based optimisation (CBO).
- Heuristic rules (Silberschatz, Korth and Sudarshan, Database System Concepts, query-processing and query-optimization chapters): push selections down the tree, push projections down, cascade and commute selections, turn "Cartesian product followed by selection" into a join, perform the most restrictive selection first, join the smaller relations first, and avoid Cartesian products.
- Equivalence rule — cascade of selection: . This is the rule that makes "push selections down" legal and is the single most impactful heuristic rewrite.
- Equivalence rule — cascade of projection: when .
- Selectivity: the fraction of tuples of a relation that satisfy a predicate. Convention used here: selectivity is the passing fraction, so a predicate is called highly selective when that fraction is small.
- Index: an auxiliary structure mapping search-key values to record locations.
A primary index is built on the ordering key; a secondary index is built on a non-ordering attribute; a dense index has an entry for every search-key value, a sparse index only for some. - Covering index / index-only scan: the index contains every field the query filters on and projects, so the engine answers from the index alone and never fetches the document or row.
- Compound (composite) index: several fields in one fixed order, e.g.
{a:1, b:-1, c:1}.
It obeys the leftmost-prefix rule: only a prefix of the index fields (starting from the first) can be used for filtering; a later field can be used only if all earlier fields are constrained by equality. - Sort by index: an index delivers rows already ordered, so the engine avoids a blocking sort (a sort that cannot emit the first row before reading all input).
The sort specification must be a prefix of the index with the same directions, or the exact reverse of the whole prefix. - Multikey index: index on an array field, storing one index entry per array element.
A multikey index cannot be used as a covering index over the array field, and one compound index cannot contain two array fields ("parallel arrays" are rejected). - Sparse index: contains entries only for documents that possess the indexed field. Partial index: contains entries only for documents satisfying a filter expression.
- TTL index: a single-field index on a date (or array of dates) with
expireAfterSeconds; a background task (runs about every 60 seconds) deletes expired documents. It is a deletion mechanism, not a query accelerator; it cannot be compound. - Hashed index: stores a hash of the key; supports equality only, and never range scans or sorts.
- Index intersection: the engine combines two indexes to satisfy one predicate; it cannot supply a sort order, and a single compound index is normally better.
- B-tree / B+-tree: height-balanced, ordered, supports equality, range, prefix and ordered retrieval. MongoDB's WiredTiger storage engine and the default
_idindex use B-trees; the_idindex is unique and cannot be dropped. - LSM-tree (Log-Structured Merge-tree): write-optimised structure — writes go to an in-memory memtable, are flushed as immutable SSTables (Sorted String Tables) and merged by compaction. Used by Cassandra, HBase, RocksDB.
- Bloom filter: probabilistic membership test per SSTable; no false negatives, false positives possible; lets a read skip SSTables that cannot contain the key.
- Ordering models: MongoDB index key order; Cassandra hashes the partition key to place the row and sorts by clustering columns inside the partition; HBase stores row keys in lexicographic byte order inside each region and has no native secondary index; Redis is an in-memory key-value store with no secondary index, ordering being provided by sorted sets; DynamoDB uses a partition key plus an optional ordered sort key.
How it works
- Parse and validate. The query text is checked against the catalog; names and types must exist.
- Translate to an internal tree. The query becomes a relational-algebra-like tree of scans, selections, projections, joins and sorts.
- Heuristic rewrite. Apply equivalence rules: cascade selections so each sits directly above its base relation, push projections to keep only needed columns, replace plus by a join, and order selections so the most selective predicate runs first.
- Enumerate access paths and join orders. For each relation choose a full scan or an index scan; for each join choose nested loop, block nested loop, sort-merge or hash join, and choose which relation is outer.
- Cost estimation. Use catalog statistics — tuple counts , block counts , distinct values , index heights — to estimate the size of every intermediate result and the block transfers of each plan.
- Choose and execute. The cheapest plan is executed. Pipelining passes tuples to the next operator immediately; operators that need all input (a blocking sort without index support, a hash build phase) materialise first.
The same pipeline decides MongoDB plan choice: candidate plans are ranked by trial runs and cached, which is cost-based in spirit (statistics come from sampled trial execution rather than a catalog).
The index access decision for a compound B-tree works as follows.
Ordering inside a distributed store (Cassandra) follows the primary-key definition: the partition key is hashed to a token that selects the node, and the clustering columns define the sorted order of rows within that partition.
A query that omits the partition key cannot be routed and needs ALLOW FILTERING (a client-side filter over a scan), which is slow and discouraged.
The classic Cassandra secondary index is stored locally on every node, so it is efficient only for low-cardinality columns and supports equality predicates only; range support arrives with SAI (Storage Attached Index) in Cassandra 4.0.
Drawing the diagram…
Drawing the diagram…
Formulas
-
Notation: = number of tuples of relation ; = number of blocks of ; = number of distinct values of attribute in ; cost counted in block transfers (Silberschatz convention).
-
Selectivity and result size: , and the estimate is .
-
Equality on a key-like attribute: , so .
-
Join size estimate for : .
-
B+-tree height, with = maximum number of children per node and = number of stored keys: , hence a lookup costs index blocks.
-
Index scan cost, with = index height, = leaf blocks touched, = matching records fetched: non-covering ; covering . Full scan .
Worked examples
Example 1 (easy, leftmost prefix). Collection with index {city:1, age:1, name:1}.
Which filters can use the index? {city:"Pune"} — yes, uses city. {city:"Pune", age:30} — yes, uses city then age. {age:30} — no, age is not a prefix. {name:"Kavita"} — no. {city:"Pune", name:"Kavita"} — partially: the index is scanned for city:"Pune" only, then name is checked in the fetched document.
Answer: only filters whose fields form a leftmost prefix use the index as an access path.
Example 2 (medium, filtering plus sorting). Index {a:1, b:-1, c:1}.
find({a:1}).sort({a:1, b:-1}): sort equals an index prefix, same directions → index provides the order, no blocking sort. Yes.find({a:1, b:2}).sort({c:1}):aandbare fixed by equality, so within that group the index is ordered bycascending. Yes.find({}).sort({a:-1, b:1, c:-1}): the exact reverse of the full pattern is also walked backwards. Yes.find({a:{$gt:5}}).sort({b:1}):ais a range, so the index cannot fixaand theborder is unusable. No.find({}).sort({b:-1}):bis not a prefix. No.
Example 3 (medium, statement type). Statement I: a sparse index in MongoDB stores entries only for documents that contain the indexed field. True. Statement II: a sparse index can serve a query filtering {b:{$exists:false}}.
False — a sparse index has no entries for documents missing b, so the very documents being sought are absent from the index. A partial index with filter {b:{$exists:false}} is the correct tool. Answer: I true, II false.
Example 4 (hard, two-step cost comparison). Relation R(A, B) has 10,000 tuples, 100 tuples per block, so . A B+-tree index on A has height , 100 entries per leaf block.
Query matches 200 tuples held in 2 leaf blocks; assume each matching record lies in a distinct data block. Step 1, full scan: 100 block transfers. Step 2, non-covering index scan: .
Since 204 > 100, the optimizer chooses the full scan. If the index covered the query, cost and the index wins easily; if the predicate were on a unique key (1 match), cost and the index also wins.
Lesson: an index is not automatically cheaper — selectivity and covering decide.
Example 5 (hard, estimate sizes). has 5,000 tuples with ; has 400 tuples with . Join on equality of A: tuples. A further selection on with selectivity 0.01 leaves tuples.
If that selection were pushed below the join, only tuples of would be joined, giving — the same final size but far less intermediate work, which is exactly why selections are pushed down.
Example 6 (match the list). A—LSM-tree: appends to a memtable, flushes immutable SSTables, merges by compaction. B—Covering index: all referenced fields present, no document fetch.
C—Clustering columns: define on-disk row order inside a Cassandra partition. D—TTL index: removes documents after expireAfterSeconds. E—Bloom filter: skips an SSTable that cannot hold the key.
Comparison
| Basis | Heuristic (rule-based) | Cost-based (CBO) |
|---|---|---|
| Input | transformation rules only | rules plus catalog statistics |
| Decision | rule always applied, e.g. push selection | compares alternatives by estimated cost |
| Cost model | none | block transfers, sometimes CPU |
| Plan quality | good, data-independent | adapts to data distribution |
| Overhead | very low | statistics maintenance, plan search |
| Failure mode | bad plan when statistics would have helped | bad plan when statistics are stale |
| Basis | B-tree | LSM-tree |
|---|---|---|
| Update style | in place, page splits | append to memtable, immutable SSTables |
| Write path | random writes | sequential writes, very fast |
| Read path | one traversal, predictable | may probe several levels (read amplification) |
| Ordering | sorted keys, easy range scan | sorted within each SSTable, merged view |
| Space | fill factor, fragmentation | compaction rewrites, tombstones |
| Best for | read-heavy, range and sort | write-heavy ingest |
| Examples | MongoDB WiredTiger, InnoDB, PostgreSQL | Cassandra, HBase, RocksDB, ScyllaDB |
| System | Primary structure | Ordering | Secondary indexes |
|---|---|---|---|
| MongoDB | B-tree | index key order, compound prefix | many; sparse, partial, multikey, TTL, hashed, text |
| Cassandra | LSM | partition key hashed, clustering columns sorted | local index, low cardinality, equality only |
| HBase | LSM | row key lexicographic bytes per region | none native; Phoenix or coprocessors |
| Redis | hash table plus skiplist | sorted sets ordered by score | none native |
| DynamoDB | managed tree/LSM | partition key hashed, sort key ordered | local and global secondary indexes |
| Index type | Definition | Trap |
|---|---|---|
| Compound | several fields, fixed order | leftmost prefix; sort direction must match or fully reverse |
| Multikey | array field, one entry per element | cannot cover the array field; no two arrays in one index |
| Sparse | entries only when the field exists | useless for $exists:false |
| Partial | entries only for a filter expression | used only when the query implies the filter |
| TTL | date field with expiry | single field only, deletion is asynchronous |
| Hashed | hash of key stored | equality only, no range, no sort |
| Text | tokenised terms | one text index per collection |
Revision summary
- Push selections down first — the cascade rule is the workhorse heuristic.
- Selectivity = fraction passing; "highly selective" means small fraction.
- Compound index rule: equality fields in any prefix, then one range field; anything after a range is not used for filtering.
- Sort rule: same directions as an index prefix, or the exact reverse of the whole prefix.
- Covered query needs every filter and projected field in the index — and
_idmust be excluded explicitly unless it is part of the index. - MongoDB
_idindex is a unique B-tree that cannot be dropped; multikey indexes cannot cover. - Sparse = field absent; TTL = date expiry; hashed = equality only.
- LSM = write-optimised, B-tree = read-optimised; Bloom filters cut LSM read cost.
- Cassandra: partition key routes, clustering columns sort; no partition key means
ALLOW FILTERING. - Cassandra secondary indexes favour low cardinality and equality predicates.
- HBase row keys are byte-lexicographic and there is no native secondary index.
- An index is chosen only when the estimated cost beats a full scan.
Previous-year exam insights
- Direct concept items ask for the default index structure in MongoDB (B-tree), the name of the array index (multikey), the purpose of clustering columns, or the definition of a covering index; answer from the precise definition, not from a product slogan.
- Leftmost-prefix questions give a compound index and four filters or sorts; check the first field of the index against the filter, then whether an earlier field is a range that blocks later fields.
- Sort questions hinge on direction: a plan can walk the index backwards, so the exact reverse of the prefix is valid, but a mixed direction such as
{a:1, b:1}against{a:1, b:-1}is not. - Statement I / Statement II items usually combine one true structural fact with one false capability claim — typical false claims are "sparse index serves
$exists:false", "multikey index covers queries", "HBase has native secondary indexes", "Cassandra secondary index is efficient for high-cardinality range queries". - Match-the-list items pair a mechanism with a description: LSM → memtable, SSTables, compaction; covering index → no document fetch; index intersection → combine two indexes, no sort support; TTL → automatic deletion.
- Assertion–Reason items require checking the reason independently: the assertion may be true while the reason gives the wrong mechanism.
- Cost-based versus heuristic questions test what each one consumes: statistics versus rules; the trap answer says CBO needs no statistics or that heuristics always give the optimal plan.
- Numeric or trace questions appear as small cost comparisons and cardinality estimates; always compute the full-scan cost and the index cost separately before choosing.
Practice at PARIKSHA
You are ready for the PARIKSHA tests of this sub-topic when you can:
- State the cascade-of-selection and cascade-of-projection rules and explain why they justify pushing operations down the tree.
- Distinguish heuristic from cost-based optimisation by input, decision rule and overhead in one line each.
- Given a compound index, list exactly which filters and which sorts it can serve, including the reverse-direction case.
- Decide whether a query is covered, naming the
_idcondition. - Explain multikey, sparse, partial, TTL and hashed indexes with one restriction each.
- Compare B-tree and LSM-tree on write path, read path, compaction and typical products.
- Trace a Cassandra query through partition key hashing and clustering order, and say when
ALLOW FILTERINGis needed. - Explain why HBase has no native secondary index and how row-key order affects range scans.
- Compute selectivity, estimated selection size and join size from given statistics.
- Compare full-scan cost with index-scan cost numerically and justify the cheaper plan.
Attempt the sub-topic test first, then the subject test.