Video in progress
How do you run a query like "find the drivers within 5 km of me" quickly across millions of points? Which spatial index algorithm do you choose?
An ordinary B-tree index over two coordinates doesn't work well. Grid-based partitioning like Geohash or S2/H3 turns a point into a single key and suits fast-changing data. An R-tree or a quadtree is good for immutable or rarely changing objects and complex shapes. In every case you take candidates from the cells and check the real distance separately.
📖 Answer
With WHERE lat BETWEEN … AND lon BETWEEN …, the DB uses a single-column index and scans the whole strip by latitude. In a city stretched from north to south, that's hundreds of thousands of rows.
Geohash. We interleave the bits of latitude and longitude to make a single string key. A common prefix means proximity. It works in an ordinary B-tree or in Redis (Redis GEOSEARCH stores a 52-bit geohash in the sorted set score). The trap: two points standing next to each other across a boundary can have completely different prefixes. That's why you always query your own cell and the 8 neighboring cells.
H3 and S2 divide the Earth's surface into hierarchical cells, hexagonal (H3) or square (S2). The cells are closer to uniform in size and neighbors are more precise. Uber created H3 precisely for driver distribution and pricing.
An R-tree (PostGIS's GiST index) groups objects in nested rectangles. It's best for polygons, roads and zones. But for 100 thousand drivers updating their location every 3 seconds, constantly rebalancing the index is expensive.
A quadtree is an in-memory alternative that keeps splitting the plane into 4 depending on density. A dense city center goes deep, a desert stays shallow.
The scheme I choose for drivers:
- The driver's position lives in memory or in Redis:
cellId → set of drivers. When the location changes, remove from the old cell and add to the new one (O(1)). - The query: the customer's cell + k rings of neighbors → candidates.
- Exact distance with Haversine, filter, sort.
- If there are no results, widen the ring.
Distance can mislead too: 5 km in a straight line and 5 km by road are different things. Re-ranking the candidates with a proper ETA service is the usual second stage.
Cell size is the main trade-off: small cells mean many neighbor queries, large cells mean many unnecessary candidates. I choose it by measuring real density, and it may even differ between the city center and the outskirts.
Sign up to mark studied questions and save your progress.