1. Gyanastra
  2. Database Systems
  3. UGC NET: NoSQL
  4. NoSQL Indexing Ordering and Query Optimization
Free lesson, no account needed 15 min read 20 practice questions after it

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: σθ1∧θ2(E)≡σθ1(σθ2(E))\sigma_{\theta_1 \land \theta_2}(E) \equiv \sigma_{\theta_1}(\sigma_{\theta_2}(E)). This is the rule that makes "push selections down" legal and is the single most impactful heuristic rewrite.
  • Equivalence rule — cascade of projection: πL1(πL2(E))≡πL1(E)\pi_{L_1}(\pi_{L_2}(E)) \equiv \pi_{L_1}(E) when L1⊆L2L_1 \subseteq L_2.
  • 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 _id index use B-trees; the _id index 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

  1. Parse and validate. The query text is checked against the catalog; names and types must exist.
  2. Translate to an internal tree. The query becomes a relational-algebra-like tree of scans, selections, projections, joins and sorts.
  3. Heuristic rewrite. Apply equivalence rules: cascade selections so each σ\sigma sits directly above its base relation, push projections to keep only needed columns, replace ×\times plus σ\sigma by a join, and order selections so the most selective predicate runs first.
  4. 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.
  5. Cost estimation. Use catalog statistics — tuple counts ∣r∣|r|, block counts brb_r, distinct values V(A,r)V(A,r), index heights — to estimate the size of every intermediate result and the block transfers of each plan.
  6. 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.

Figure. The flowchart shows query processing from query text to execution; notice that heuristic rewrite precedes access-path and join-order enumeration, and cost estimation uses statistics to choose the cheapest plan.
Figure. Notice the leftmost-prefix match and ordered index read; if all needed fields are in the index, it uses an index-only scan, otherwise it fetches the record by pointer.

Formulas

  • Notation: ∣r∣|r| = number of tuples of relation rr; brb_r = number of blocks of rr; V(A,r)V(A,r) = number of distinct values of attribute AA in rr; cost counted in block transfers (Silberschatz convention).

  • Selectivity and result size: s(θ)=∣σθ(r)∣∣r∣s(\theta)=\dfrac{|\sigma_\theta(r)|}{|r|}, and the estimate is ∣σθ(r)∣≈s(θ)⋅∣r∣|\sigma_\theta(r)| \approx s(\theta)\cdot|r|.

  • Equality on a key-like attribute: s(A=v)=1V(A,r)s(A=v)=\dfrac{1}{V(A,r)}, so ∣σA=v(r)∣≈∣r∣V(A,r)|\sigma_{A=v}(r)| \approx \dfrac{|r|}{V(A,r)}.

  • Join size estimate for r⋈r.A=s.Bsr \bowtie_{r.A=s.B} s:   ∣r⋈s∣≈∣r∣×∣s∣max⁡(V(A,r), V(B,s))\;|r \bowtie s| \approx \dfrac{|r|\times|s|}{\max\big(V(A,r),\,V(B,s)\big)}.

  • B+-tree height, with mm = maximum number of children per node and nn = number of stored keys: h≤log⁡⌈m/2⌉ ⁣(n+12)h \le \log_{\lceil m/2 \rceil}\!\left(\dfrac{n+1}{2}\right), hence a lookup costs O(log⁡mn)O(\log_m n) index blocks.

  • Index scan cost, with hh = index height, bleafb_{leaf} = leaf blocks touched, nmatchn_{match} = matching records fetched: non-covering C=(h−1)+bleaf+nmatchC=(h-1)+b_{leaf}+n_{match}; covering C=(h−1)+bleafC=(h-1)+b_{leaf}. Full scan C=brC=b_r.

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}): a and b are fixed by equality, so within that group the index is ordered by c ascending. 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}): a is a range, so the index cannot fix a and the b order is unusable. No.
  • find({}).sort({b:-1}): b is 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 br=100b_r=100. A B+-tree index on A has height h=3h=3, 100 entries per leaf block.
Query σA=25(R)\sigma_{A=25}(R) 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: (h−1)+bleaf+nmatch=2+2+200=204(h-1)+b_{leaf}+n_{match}=2+2+200=204.
Since 204 > 100, the optimizer chooses the full scan. If the index covered the query, cost =2+2=4=2+2=4 and the index wins easily; if the predicate were on a unique key (1 match), cost =2+1+1=4=2+1+1=4 and the index also wins.
Lesson: an index is not automatically cheaper — selectivity and covering decide.

Example 5 (hard, estimate sizes). r(A,B)r(A,B) has 5,000 tuples with V(A,r)=100V(A,r)=100; s(A,C)s(A,C) has 400 tuples with V(A,s)=20V(A,s)=20. Join on equality of A: ∣r⋈s∣=(5000×400)/max⁡(100,20)=2,000,000/100=20,000|r \bowtie s| = (5000\times400)/\max(100,20)=2{,}000{,}000/100=20{,}000 tuples. A further selection on r.Br.B with selectivity 0.01 leaves 20,000×0.01=20020{,}000\times0.01=200 tuples.
If that selection were pushed below the join, only 5000×0.01=505000\times0.01=50 tuples of rr would be joined, giving (50×400)/max⁡(100,20)=200(50\times400)/\max(100,20)=200 — 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

BasisHeuristic (rule-based)Cost-based (CBO)
Inputtransformation rules onlyrules plus catalog statistics
Decisionrule always applied, e.g. push selectioncompares alternatives by estimated cost
Cost modelnoneblock transfers, sometimes CPU
Plan qualitygood, data-independentadapts to data distribution
Overheadvery lowstatistics maintenance, plan search
Failure modebad plan when statistics would have helpedbad plan when statistics are stale
BasisB-treeLSM-tree
Update stylein place, page splitsappend to memtable, immutable SSTables
Write pathrandom writessequential writes, very fast
Read pathone traversal, predictablemay probe several levels (read amplification)
Orderingsorted keys, easy range scansorted within each SSTable, merged view
Spacefill factor, fragmentationcompaction rewrites, tombstones
Best forread-heavy, range and sortwrite-heavy ingest
ExamplesMongoDB WiredTiger, InnoDB, PostgreSQLCassandra, HBase, RocksDB, ScyllaDB
SystemPrimary structureOrderingSecondary indexes
MongoDBB-treeindex key order, compound prefixmany; sparse, partial, multikey, TTL, hashed, text
CassandraLSMpartition key hashed, clustering columns sortedlocal index, low cardinality, equality only
HBaseLSMrow key lexicographic bytes per regionnone native; Phoenix or coprocessors
Redishash table plus skiplistsorted sets ordered by scorenone native
DynamoDBmanaged tree/LSMpartition key hashed, sort key orderedlocal and global secondary indexes
Index typeDefinitionTrap
Compoundseveral fields, fixed orderleftmost prefix; sort direction must match or fully reverse
Multikeyarray field, one entry per elementcannot cover the array field; no two arrays in one index
Sparseentries only when the field existsuseless for $exists:false
Partialentries only for a filter expressionused only when the query implies the filter
TTLdate field with expirysingle field only, deletion is asynchronous
Hashedhash of key storedequality only, no range, no sort
Texttokenised termsone text index per collection

Revision summary

  1. Push selections down first — the cascade rule σθ1∧θ2≡σθ1(σθ2)\sigma_{\theta_1\land\theta_2}\equiv\sigma_{\theta_1}(\sigma_{\theta_2}) is the workhorse heuristic.
  2. Selectivity = fraction passing; "highly selective" means small fraction.
  3. Compound index rule: equality fields in any prefix, then one range field; anything after a range is not used for filtering.
  4. Sort rule: same directions as an index prefix, or the exact reverse of the whole prefix.
  5. Covered query needs every filter and projected field in the index — and _id must be excluded explicitly unless it is part of the index.
  6. MongoDB _id index is a unique B-tree that cannot be dropped; multikey indexes cannot cover.
  7. Sparse = field absent; TTL = date expiry; hashed = equality only.
  8. LSM = write-optimised, B-tree = read-optimised; Bloom filters cut LSM read cost.
  9. Cassandra: partition key routes, clustering columns sort; no partition key means ALLOW FILTERING.
  10. Cassandra secondary indexes favour low cardinality and equality predicates.
  11. HBase row keys are byte-lexicographic and there is no native secondary index.
  12. 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:

  1. State the cascade-of-selection and cascade-of-projection rules and explain why they justify pushing operations down the tree.
  2. Distinguish heuristic from cost-based optimisation by input, decision rule and overhead in one line each.
  3. Given a compound index, list exactly which filters and which sorts it can serve, including the reverse-direction case.
  4. Decide whether a query is covered, naming the _id condition.
  5. Explain multikey, sparse, partial, TTL and hashed indexes with one restriction each.
  6. Compare B-tree and LSM-tree on write path, read path, compaction and typical products.
  7. Trace a Cassandra query through partition key hashing and clustering order, and say when ALLOW FILTERING is needed.
  8. Explain why HBase has no native secondary index and how row-key order affects range scans.
  9. Compute selectivity, estimated selection size and join size from given statistics.
  10. Compare full-scan cost with index-scan cost numerically and justify the cheaper plan.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2