VII · Spatial structures

Z-order / Hilbert curve

Linearise space, preserve locality.

The story

Morton encoded 2D coordinates by interleaving the bits of x and y — points near each other in 2D land near each other in 1D, with discontinuities at quadrant boundaries. The Hilbert curve does the same thing without the jumps. Both let you index multi-dimensional data with a single B-tree.

How it works

Z-order: interleave the bits of (x, y) → one integer. Sort by that integer; nearby points cluster. Hilbert: a continuous curve that visits every grid cell with no jumps; more expensive to compute but better locality.

Where it lives

Spatial keys in DynamoDB, Bigtable. Geohashes (a Z-order variant). NUMA-aware allocators. Database multi-dim index. PostGIS GiST when SP-GIST is faster.

The key insight

A space-filling curve turns multi-dimensional indexing into a single-key sort — every existing B-tree becomes a spatial index. Geohashes (used by every "nearby" query in social apps) are exactly this.