Exercise 2: Why PostGIS Distance Queries Need GiST, Not B-Tree — Possible Solution ==================================================================== THE CHAPTER'S OWN CONNECTION ------------------------------ Per this chapter, PostGIS "adds real geometry and geography types... hundreds of spatial functions... and spatial indexing built directly on GiST — a direct, concrete payoff of postgres1-7's own material." The worked example builds a GiST index (CREATE INDEX idx_stores_location ON stores USING GIST (location);) specifically to make the ST_DWithin "find stores within 5km" query fast. WHY A B-TREE CAN'T SUPPORT THIS QUERY EFFICIENTLY ------------------------------ Per postgres1-7's own material (referenced directly by this chapter), a B-tree index is built around a strict, total ordering of single values — efficient for "is this value equal to X" or "is this value between X and Y" questions, because those rely on a value's position in a single, linear order. "Is this point within 5km of this other point" is not a question about linear ordering at all — a two- dimensional (or geographic) distance relationship has no way to be represented as a single sortable line such that "nearby" points always end up adjacent to each other in that ordering. Two points could be close in actual physical distance while being far apart in almost any simple one-dimensional sort order (e.g. sorted by latitude alone, two points at very different longitudes but the same latitude would appear adjacent despite being far apart in real distance). WHY GiST CAN SUPPORT IT ------------------------------ Per postgres1-7's own material, GiST "supports a broader, extensible class of queries than GIN — nearest-neighbor search, geometric and spatial queries." GiST's own structure is specifically built to be extensible to non-linear, spatial-style comparisons (distance, containment, intersection) rather than being locked into strict total ordering. This chapter's own example applies exactly that flexibility to real geographic distance: the GiST index on the location column can efficiently narrow down candidate stores that MIGHT be within 5km without needing to compute the exact distance for every single store in the table, the same underlying mechanism that let postgres1-3's own range-overlap exclusion constraint work efficiently for a completely different kind of "non-linear" comparison. WHY THIS WORKS AS AN ANSWER ------------------------------ It explains precisely why a B-tree's strict-ordering design can't represent a distance relationship, and connects GiST's own extensible, spatial-query-capable structure (already introduced in postgres1-7) to why it's specifically what PostGIS's own distance queries depend on.