Spatial indexing: geohash and H3
Phase 2 finale. A spatial index answers "what is near here?" without scanning everything — and the trick is to give every place a cell ID, so nearby places share an ID or a prefix and the search becomes a lookup. You have met one already: the geohash from Lesson 25. This lesson puts it next to its modern rival, Uber's H3.
The code
import h3 # H3: every point falls in exactly one hexagonal cell per resolution cell = h3.latlng_to_cell(40.3573, -74.6558, 9) # Princeton, resolution 9 print(cell) # the cell ID for Princeton at res 9 # The neighbours are one call away: this cell plus its ring of 6 ring = h3.grid_disk(cell, 1) print(len(ring)) # 7
In practice
Geohash interleaves the bits of longitude and latitude into one short string. Nearby points usually share a prefix, so a sorted table or a B-tree can answer "everything starting with dr5r" almost instantly — that is why Lesson 25 could use it as a partition key. Its cells are rectangles, though: a point near a cell edge can be metres from a neighbour whose geohash shares nothing, so real searches check the 8 surrounding cells too.
H3 tiles the Earth with hexagons instead, at 16 resolutions (0 is continent-sized, 15 is a few square metres; 9 is roughly a city block, about 0.1 km²). Hexagons fix the rectangle's two flaws: all six neighbours sit at the same distance, and cells keep nearly the same area everywhere on Earth. The cell ID works everywhere a key works: as a partition folder (Lesson 25), as a GROUP BY for counting events per cell, and as a join key between two datasets that share no other geography.
Partition or index? Same IDs, different job. Partitioning is how the files are laid out on disk; indexing is how you find rows fast at query time. In practice the two blur together — partition a lake by H3 cell and the partition key is your index for area queries.
Python bridge: an H3 cell ID is just a categorical column. Add it to a DataFrame once, and counting, grouping and joining by place become ordinary pandas — no geometry math in the loop.
Further reading
H3 Geospatial Indexing: How Uber Finds Nearby Drivers — DEV (geohash and H3 side by side, with the neighbour problem drawn out)
Try it
Practice question: given a pandas DataFrame stations with lat and lon columns, add an H3 cell column at resolution 7 and count the stations in each cell, biggest cell first — the Lesson 25 geohash exercise, hexagons this time.
Show answer
stations["h3_7"] = stations.apply(
lambda r: h3.latlng_to_cell(r.lat, r.lon, 7), axis=1)
print(stations.groupby("h3_7").size()
.sort_values(ascending=False))
Result: one row per occupied resolution-7 cell (each about 5 km²) with its station count, biggest first. Same shape as the geohash answer in Lesson 25 — swap the cell system and the counting code does not change, which is the whole point of a cell index. And that is Phase 2 complete: spatial SQL, DuckDB, GeoParquet, partitioning, Sedona, raster and vector, COGs, and indexing.