skip to content

In PostgreSQL, how does a GiST or SP-GiST index answer ORDER BY location <-> point '(10,20)' LIMIT 3, and how do those two methods differ?

level: middleimportance: nice to knowfreq 28%

answer

  1. an ordering operator, not a filter
  2. nearest bounding box first
  3. stops at the LIMIT
  4. balanced and overlapping, or partitioned

basics

~20 s

GiST and SP-GiST both list <-> as an ordering operator for points, so an index scan returns rows nearest-first and stops at the LIMIT. GiST is a balanced, multicolumn tree of overlapping bounding keys; SP-GiST builds single-column, non-overlapping quad-trees, k-d trees or tries.

solid answer

~50 s

In PostgreSQL `<->` between points is the distance operator, and GiST's `point_ops` and SP-GiST's `quad_point_ops` and `kd_point_ops` list it as an **ordering operator**. With `ORDER BY location <-> point '(10,20)' LIMIT 3`, the planner can choose a plain Index Scan whose plan shows an `Order By` condition: the index walks its tree using lower bounds on the distance to each subtree, emits stations nearest-first, and stops after three rows instead of sorting the whole table. **GiST** is a balanced tree whose internal entries cover their children and may overlap, such as bounding boxes around groups of points; it can be multicolumn and indexes many shape and range types. **SP-GiST** partitions space into non-overlapping, unbalanced pieces (quad-tree by default, k-d tree with `kd_point_ops`) and indexes a single column. Note that `<->` on `point` is planar distance, not distance on the Earth.

go deeper

for a junior

Recall that nearest-neighbour queries on geometry use a GiST index with ORDER BY col <-> target LIMIT k, and that a B-tree cannot do it.

for a middle

Explain ordering operators, how the index walks bounding boxes nearest-first and stops at the LIMIT, and which point operator classes GiST and SP-GiST ship.

for a senior

Choose between GiST and SP-GiST from the data's shape, notice when a filter makes the KNN scan read far more entries, and flag planar distance on latitude and longitude.

for a principal

Decide whether core geometric types suffice or a geospatial extension should own location data, weighing accuracy, index choice and the cost of migrating later.

## The query shape A **k-nearest-neighbour** (KNN) query asks for the k rows closest to a target. For weather stations stored with a `point` column: ```sql SELECT station_id, name FROM stations ORDER BY location <-> point '(10,20)' LIMIT 3; ``` Without a suitable index, PostgreSQL computes the distance for every station and keeps the three smallest. With one, it reads only the part of the index near the target. ## Ordering operators An index can serve this only if its **operator class** lists the operator as an **ordering operator**, not just as a searchable one. The core tables show: | Method | Operator class | Ordering operator for points | |---|---|---| | GiST | `point_ops` (default for `point`) | `<-> (point, point)` | | SP-GiST | `quad_point_ops` (default for `point`) | `<-> (point, point)` | | SP-GiST | `kd_point_ops` | `<-> (point, point)` | GiST's box, circle and polygon classes, and SP-GiST's `poly_ops`, offer `<->` against a point as well. A B-tree has no ordering operators of this kind; GIN and BRIN have none at all, because they only produce bitmap scans. The ORDER BY item must be `indexed_column <-> constant` using that operator. When it is, the plan shows an **Index Scan** with an `Order By` line next to the index, and no Sort node. ## How the scan finds the nearest rows GiST's `point_ops` stores **bounding boxes** in its internal entries. Each operator class supplies a **distance** function, and for an internal entry that function must never return more than the distance to any child beneath it. The scan: 1. Computes a lower-bound distance from the target to each entry at the top of the tree. 2. Keeps entries in a queue ordered by that distance and always expands the closest one. 3. Emits a leaf entry when nothing still queued could be closer. 4. Stops as soon as the `LIMIT` is satisfied. If a class's distance is only an approximation for leaf entries, the executor recomputes the exact distance and reorders as needed, so the result is still correct. ## GiST versus SP-GiST | Aspect | GiST | SP-GiST | |---|---|---| | Tree shape | balanced | non-balanced | | Partitions | may overlap (bounding predicates) | do not overlap (space is divided) | | Typical structures | R-tree-like bounding boxes | quad-tree, k-d tree, radix tree | | Columns per index | several | one | | Core point classes | `point_ops` | `quad_point_ops`, `kd_point_ops` | | Other uses | boxes, polygons, ranges, `inet`, `tsvector` | text prefixes (`text_ops`), ranges, `inet` | **GiST** fits data whose values overlap, such as shapes and ranges, because its entries can cover overlapping regions. **SP-GiST** fits data that divides cleanly, such as points or strings sharing prefixes; searches well matched to its partitioning rule can be very fast. For a table of points, both work, so measure on your own data. ## Caveats for a station map - **Planar distance.** `point <-> point` is the straight-line distance in the plane. If `location` holds longitude and latitude in degrees, the ordering is only an approximation of distance on the Earth; geographic distance needs an extension with its own geography types and GiST classes. - **Filters plus ordering.** With `WHERE tags @> ARRAY['coastal']` added, the planner may keep the KNN index scan and apply the tag test as a filter, discarding non-matching stations as they stream out, so a rare tag means many index entries read before three rows qualify. It may instead pick the GIN index on `tags` and sort the survivors; compare both plans. - **Ranges and exclusion constraints** also use GiST, but those belong to the range-type and constraint leaves. ## Building and checking the index 1. Create one of the two: `CREATE INDEX stations_location_gist ON stations USING gist (location);` or `CREATE INDEX stations_location_spgist ON stations USING spgist (location);` (which uses `quad_point_ops`). 2. Run the query under `EXPLAIN (ANALYZE)` and look for an **Index Scan** on that index with an `Order By` line and no Sort node above it. 3. If a Sort appears instead, check that the `ORDER BY` item is exactly the indexed column `<->` a constant, not a function wrapped around either side or a distance computed by hand from coordinates. 4. Compare build time, size and query time of the two methods on a copy of the real station data before settling on one.

  • Why can't a GIN index on location serve this ORDER BY, even though GIN is also extensible?
    GIN only supports bitmap scans, which hand back matching pages in physical order, and no GIN operator class defines ordering operators. A KNN query needs an index that can return entries one by one in distance order, which GiST and SP-GiST provide through ordering operators such as `<->`.
  • Your stations store longitude and latitude in a point column. What is wrong with ranking them by location <-> point(...)?
    `<->` on `point` computes planar Euclidean distance, so it treats a degree of longitude as the same length everywhere. Near the poles that distorts the ranking. It may be acceptable for a small region, but true distance on the Earth needs a geospatial extension's geography type and its own GiST classes.

  • A B-tree on location can serve ORDER BY location <-> point(...).
  • KNN with GiST first finds all rows within a radius, then sorts them.
  • SP-GiST supports multicolumn indexes just like GiST.
  • kd_point_ops is the default SP-GiST class for points.
  • point <-> point returns distance in kilometres on the Earth.