Geospatial Indexing
Turn latitude and longitude into a sortable key so "what is near me" becomes a range scan.
A user opens your app in London and asks for restaurants within 5 kilometres.
You write what looks obvious: select everything where latitude is between two numbers and longitude is between two numbers. You have indexed both columns. It returns in 8 milliseconds on your laptop against 3,000 rows.
In production, against 8 million rows, it takes 1.9 seconds. Your database used the latitude index, pulled back 40,000 rows in that band stretching right across Europe, and threw away 39,000 of them one at a time for having the wrong longitude.
Both columns are indexed and the query is still doing almost all its work by hand. Understanding why is the whole chapter, and the reason a separate family of indexes exists for this.
Lessons
4 in this chapter- Why Two Dimensions Break IndexesA B-tree sorts on one axis. Nearness needs both at once.2 min
- GeohashInterleave the bits of both coordinates and closeness becomes a shared prefix.2 min
- The Boundary ProblemTwo shops across the street from each other can share no prefix at all.2 min
- Quadtrees and HexagonsFixed grids waste space on empty land and choke on dense cities.3 min