Multidimensional Indexes

The two index families Parts I and II cannot express. This part is what happens when the query is a box rather than a range — no total order on a plane preserves proximity, so the index must either linearize the space or build a tree over regions. The Full-text indexes part is what happens when one row produces two hundred keys — and the answer turns out to be Part I's LSM tree, wearing different nouns.

Why a composite B-tree isn't two-dimensional

Take the canonical query — every point of interest inside a map viewport:

SELECT * FROM poi
WHERE lat BETWEEN  51.500 AND  51.550
  AND lng BETWEEN  -0.145 AND  -0.075;

With CREATE INDEX ON poi (lat, lng) the B-tree's sort order is lexicographic: every row with lat = 51.5001 — at every longitude on Earth — sorts before any row with lat = 51.5002. The index can seek to the start of the latitude band and stop at its end. Inside the band it can do nothing, because the rows with the right longitude are scattered uniformly through it.

50 M points of interest, 8 KB pages, ~24 B per index entry

Query box          51.500–51.550 lat  ×  −0.145–−0.075 lng   (≈ 5.5 km × 4.9 km)

Rows actually in the box                                  ≈      1,200
Rows in the latitude band alone (all longitudes)          ≈    310,000
Index entries walked                                      ≈    310,000    ← 260× the answer
Index pages read       310,000 × 24 B / 8 KB              ≈        910    ≈ 7 MB
Heap fetches                                              ≈      1,200

Note what the waste is and isn't. Because lng is in the index key, the engine applies it as a filter while walking the leaves, so the heap is touched only 1,200 times — this is not a heap-I/O problem. The cost is 310,000 index tuples examined to return 1,200, and it compounds multiplicatively: add altitude or a timestamp as a third dimension and only the first one is ever a search bound. The other two are filters that have already been paid for.

The root cause is not a missing feature. It is a theorem: there is no total order on the plane that preserves proximity. Any mapping from ℝ² to ℝ must place some pairs of neighbours far apart, and a B-tree can exploit nothing except a total order. Multidimensional indexing is the study of how little proximity you have to lose.

A 2-D range query, a box on latitude by longitude, has two escapes. Family 1 linearizes the space with Z-order, Hilbert or geohash: the result is one ordered key that works in any B-tree or LSM, but the box becomes many ranges. Family 2 builds a tree over regions, an R-tree or GiST: sibling boxes may overlap, so a search follows several paths, and the structure needs in-place page updates. Both return candidates, a superset of the answer, and both converge on a recheck of the exact predicate against the real geometry.
Two escapes from the no-total-order theorem — both end in a recheck

Family 1 — linearize: space-filling curves

If the problem is that no order preserves proximity, pick the order that loses the least and then use the indexes you already have. The Z-order curve (Morton code) does it by interleaving the bits of the coordinates:

Morton encoding of the point x equals 5, y equals 3, with 4-bit coordinates. y is 0011 and x is 0101. The bits are interleaved as y3 x3 y2 x2 y1 x1 y0 x0, giving 0 0, 0 1, 1 0, 1 1, which is binary 00011011, decimal 27. z of 5, 3 is 27: a single integer key storable in any B-tree or LSM.
Morton encoding: interleave the bits of y and x into one integer key

What that ordering looks like on a 4×4 grid — and where it breaks:

A 4 by 4 grid labelled with Z-order values. Row y equals 0 reads 0, 1, 4, 5; row 1 reads 2, 3, 6, 7; row 2 reads 8, 9, 12, 13; row 3 reads 10, 11, 14, 15. The curve visits 0 to 3 as one 2 by 2 block and 4 to 7 as the next, so locality mostly holds. The tear: z equals 7 is cell 3, 1 and z equals 8 is cell 0, 2 — consecutive on the curve, at opposite ends of the grid.
Z-order on a 4×4 grid — local inside each quadrant, torn between them

That tear happens at every power-of-two boundary, at every scale — which is why a box query does not become one range scan.

a 2×2 box in the middle of the grid — x ∈ [1,2], y ∈ [1,2]

cells:   (1,1) = 3    (2,1) = 6    (1,2) = 9    (2,2) = 12

ranges:  [3,3]  [6,6]  [9,9]  [12,12]        ← four seeks for four cells

A box that straddles the top-level split is the worst case: it is cut by
every level of the curve at once.

Real implementations compute the covering ranges by recursive quadrant decomposition, then cap the number of ranges and merge ranges separated by small gaps — deliberately buying false positives (cells outside the box, discarded by the recheck) in exchange for fewer seeks. That cap is the tuning knob: too low and you scan half the table, too high and you issue a thousand tiny range reads. GeoMesa exposes it directly over Accumulo/HBase; every Z-order-over-KV design has some version of it.

The Hilbert curve is the better curve and the more expensive one. It has no tears — consecutive indices are always adjacent cells — so the same box decomposes into markedly fewer, longer ranges. The price is that encoding is a per-bit-pair state machine rather than one bit-interleave, and range decomposition is correspondingly harder. It shows up where build cost is amortized over many queries: Google's S2 lays a Hilbert curve over the six faces of a cube projected onto the sphere; PostGIS supplies a Hilbert sort-support function so PostgreSQL 14+ can build a GiST index by sorting instead of inserting one geometry at a time; Databricks' liquid clustering uses Hilbert order where Iceberg's rewrite_data_files exposes Z-order.

Geohash: linearization with a string interface

A geohash is the Z-order curve of (lng, lat) with a base-32 alphabet layered on top: interleave the bits, then encode 5 bits per character. Each additional character narrows the cell, so a shared prefix means a shared bounding box — and a box query becomes a prefix scan, which is the one operation every ordered key-value store on Earth already supports.

Prefix lengthCell size (near the equator)Typical use
15,000 km × 5,000 kmcontinent
3156 km × 156 kmmetro region
54.9 km × 4.9 kmcity district
61.2 km × 0.61 kmneighbourhood
7153 m × 153 mcity block
838 m × 19 mbuilding

Family 2 — R-trees: a balanced tree whose keys are regions

The other escape refuses to linearize. An R-tree keeps the B-tree's shape — fixed-size pages, height-balanced, split on overflow — but its keys are minimum bounding rectangles instead of scalars:

Leaf entry(MBR of the geometry, TID)
Internal entry(MBR covering all children, page ptr)
Searchdescend every child whose MBR intersects the query

fanout and height — 50 M geometries

8 KB page;  2-D MBR of float8 = 4 × 8 B = 32 B;  + 8 B child pointer = 40 B
→ ~200 entries per page, ~140 at a 70 % fill factor

  leaves     50,000,000 / 140   ≈  357,000 pages   ≈ 2.9 GB
  level 2       357,000 / 140   ≈    2,550 pages
  level 1         2,550 / 140   ≈       19 pages
  root                                   1 page

4 levels — the same height as a B-tree over 50 M rows.

And here is the one structural break from every index in Part II: sibling MBRs are allowed to overlap. A B-tree's separator keys partition the key space, so a point belongs to exactly one child and a point lookup follows exactly one path — that is what makes its O(log n) a worst case and not an average. An R-tree's boxes partition nothing. A query point can fall inside three sibling boxes, and the search must descend all three. The height is bounded; the number of paths is bounded by nothing but the data.

So an R-tree's query performance is entirely a function of how good its boxes are, measured on two axes: overlap (how much sibling MBRs intersect — each overlap is a potential extra subtree visit) and dead space (area an MBR covers but contains no geometry — each is a potential wasted descent). Both are decided by heuristics at insert time:

  1. ChooseSubtree. Descend into the child whose MBR requires the least area enlargement to contain the new entry; break ties by smallest existing area. Note that this is a greedy local decision with no ability to reconsider — which is why insertion order affects the final tree's quality.
  2. Split. When a page overflows, partition its entries into two groups. Guttman's original quadratic split picks the two entries that would waste the most area if grouped together, then assigns the rest greedily. It is O(n²) in the page's entry count — a few hundred — so it is cheap in absolute terms and still the dominant cost of an insert.
  3. The R*-tree refinement. Minimise overlap and perimeter as well as area, and on the first overflow of a node do forced reinsertion — remove the 30 % of entries farthest from the node's centre and reinsert them from the root rather than splitting. Inserts get measurably slower; queries get substantially faster, because the tree is continuously being un-degraded. This is the R-tree in most production systems.

Bulk loading beats incremental insertion, badly. Sort-Tile-Recursive (STR) packing — sort by x, cut into ⌈√(N/f)⌉ vertical slices, sort each slice by y, pack leaves to capacity — produces a near-zero-overlap tree in one pass. For static or rebuild-able spatial data the same query against an STR-packed tree can be several times faster than against a tree built by 50 M individual inserts. This is the SSTables and sparse indexes part's lesson in a different shape: written once, already sorted is a structurally better artifact than mutated into existence.

Nearest neighbour is the query shape that only this family gives you. Best-first search (Hjaltason–Samet): push the root onto a priority queue ordered by mindist to the query point; repeatedly pop the closest entry, expanding internal nodes and pushing their children. When the popped entry is a leaf record, it is provably the next nearest neighbour — no radius guess required. That is what ORDER BY geom <-> point LIMIT 10 compiles to in PostGIS. On a Z-curve you have no equivalent: you must guess a radius, scan the covering ranges, and widen and re-scan if you came up short.

GiST, SP-GiST, and why the index alone is never the answer

PostgreSQL ships no R-tree. It ships GiST, a generic balanced-tree skeleton in which the tree walk is the built-in part and the semantics are supplied by the operator class:

Opclass functionWhat it answers
consistentCould this subtree possibly contain a match? (may answer "maybe")
unionThe summary key covering a set of entries
penaltyCost of inserting here — the enlargement heuristic
picksplitHow to divide an overflowing page
compress / decompressLossy summary of the real value ↔ back again

Plug in bounding boxes and you have an R-tree. Plug in ranges and you get && over tsrange. Plug in signatures and you get tsvector phrase search. The index type is the traversal, not the data type — which is exactly the same factoring idea as the Compaction strategies part's pluggable compaction policies over one immutable-file substrate.

The consequence that matters operationally: because compress is lossy, a GiST scan is lossy, and the executor must run two phases.

Bitmap Heap Scan on poi
  Recheck Cond: (geom && '...'::geometry)          ← MBR overlap: cheap, conservative
  Filter: st_contains(geom, '...'::geometry)        ← exact geometry: expensive, correct
  ->  Bitmap Index Scan on poi_geom_gist
        Index Cond: (geom && '...'::geometry)

Filter and refine. The index returns a cheap conservative superset; exactness is bought with heap fetches and real geometric predicates. So a spatial query's cost is dominated not by tree height but by how many false positives the MBRs let through — a long thin diagonal road has an MBR covering an enormous empty area, and every query over that area pays to fetch and reject it. This is the same shape as the Bloom filters part's Bloom filter (cheap "maybe," expensive confirmation) and the same shape as the trigram recheck in the Full-text indexes part.

SP-GiST is the other skeleton: space-partitioning, non-balanced, and — the important word — disjoint. Quadtrees, k-d trees, radix tries. Because the partitions don't overlap, a point lookup follows exactly one path again, recovering the property R-trees gave up. The price is that the tree's depth is data-dependent rather than balanced by construction, so a pathological distribution makes it deep. PostgreSQL uses it for point, inet, and text prefix search.

Which family lives in which engine

Composite B-treeZ-order / geohash keyR-tree (GiST)SP-GiST
What it really is1-D index on a concatenated key1-D index on an interleaved keyBalanced tree over overlapping regionsUnbalanced tree over disjoint regions
Box queryScans the whole first-dimension bandMany ranges + merge toleranceDescends all intersecting subtreesOne path per point, several per box
False positivesNone (exact key comparison)Yes — merged ranges and cell granularityYes — MBR is a lossy summaryOnly at partition granularity
k-NNNoOnly by guessing a radiusYes — exact, incrementalYes
Works in an LSM engine?YesYes — it is just a keyNo — splits need in-place page updatesNo
Update costOne entryOne entryEnlargement + split heuristics per insertCheap insert, possible deep path

That fifth row is the whole reason the linearization family exists at scale. An R-tree requires mutable pages: a split rewrites the parent, forced reinsertion rewrites entries from the root. You will not find an R-tree inside RocksDB, Cassandra, or DynamoDB. Spatial support in an append-only engine is almost always a linearized key in the row key — geohash prefixes in HBase, S2 cell IDs in a Bigtable row key, a Z-order clustering key in a lakehouse table — precisely because a linearized key demands no new machinery from the storage engine at all. It is a key, and Part I's engines already store keys.

It was never really about maps — and where it stops working

The geospatial framing hides the general case. Any conjunction of range predicates is a box in k dimensions, and everything above applies verbatim:

WHERE temperature BETWEEN 20 AND 25
  AND observed_at BETWEEN '2026-06-01' AND '2026-06-30'     ← 2-D box over weather observations

WHERE price BETWEEN 40 AND 80
  AND rating >= 4.2
  AND distance_km <= 5                                       ← 3-D box over a product catalogue

A composite B-tree on (temperature, observed_at) fails here for exactly the reason it failed on (lat, lng): it scans every observation in the temperature band and filters by date. Postgres's answer for the second case is often a GiST index over a cube or a set of ranges; the answer in a warehouse is the Analytics and table formats clustering trick, not an index at all.

And then it stops. As k grows, a box that keeps 10 % of the range in each dimension keeps 0.1k of the volume — selectivity either collapses to nothing or, far more commonly, the MBRs of every subtree overlap so thoroughly that a query must visit them all. Empirically, R-trees lose to a sequential scan somewhere around 10–20 dimensions. Above that, exact multidimensional indexing is not available at any price, which is why similarity search over 384–1536-dimensional embeddings abandons exactness entirely: HNSW's navigable small-world graph, IVF-PQ's coarse centroids plus quantized residuals. The Full-text indexes part arrives at the same wall from the other direction.

The Invariants

  • Guarantees: A genuinely multidimensional index prunes on every dimension simultaneously, so a box query's cost tracks the size of the answer rather than the width of the widest single-dimension band — and an R-tree keeps a B-tree's height bound while doing it.
  • Does not guarantee: A single search path, or a correct answer from the index alone. Overlapping MBRs make the number of subtrees visited data-dependent and unbounded in the worst case; linearized keys return cells, not boxes. Every result must be rechecked against the real predicate, and the recheck is where the time goes.