GiST and SP-GiST
trees of bounding boxes for ranges, geometry and nearest-neighbour search.
- address
- everything.index_internals.gist_and_spgist
- part
- part 13, inside indexes
- chapter
- chapter 9 of 12
- reading time
- 9 min
GiST is a balanced tree where each inner entry is a bounding box (more generally, a predicate) that covers everything below it. boxes can overlap, so a search may go down several branches. three functions decide everything: consistent (could this subtree match?), penalty (which subtree grows least if this goes in?) and picksplit (how to cut a full page in two). SP-GiST partitions space instead, into pieces that never overlap: quadtrees, k-d trees, tries. both can walk the tree in distance order, which is how ORDER BY p <-> point finds nearest neighbours without sorting.
the picture
you know what GiST and SP-GiST serve: overlap, containment and distance on ranges, geometry, and text prefixes. a b-tree can't, because points on a plane don't have one sort order that keeps neighbours together. so instead of separator keys, GiST's inner pages hold shapes.
think of a map with boxes drawn on it: "everything in this rectangle is on page 3". to find what's near you, check which boxes could contain it, and only open those pages. the boxes are allowed to overlap, which makes inserting easy (put it in the box that grows least) and searching a bit harder (maybe open two).
here's a real GiST index on 1,000 points, and the boxes its root keeps for its eight leaf pages:
read it yourself
pageinspect reads GiST pages pg 14+:
CREATE TABLE pts AS
SELECT g AS id, point(abs(hashint4(g)) % 100, abs(hashint4(-g)) % 100) AS p
FROM generate_series(1, 1000) AS g;
CREATE INDEX pts_gist ON pts USING gist (p);
SELECT b AS blkno, o.flags, o.rightlink,
(SELECT count(*) FROM gist_page_items(get_raw_page('pts_gist', b), 'pts_gist')) AS items
FROM generate_series(0, pg_relation_size('pts_gist') / 8192 - 1) AS b,
gist_page_opaque_info(get_raw_page('pts_gist', b)) AS o
ORDER BY b;| blknoint8 | flagstext[] | rightlinkint8 | itemsint8 |
|---|---|---|---|
| 0 | {} | 4294967295 | 8 |
| 1 | {leaf} | 4294967295 | 176 |
| 2 | {leaf} | 1 | 113 |
| 3 | {leaf} | 2 | 79 |
| 4 | {leaf} | 3 | 85 |
| 5 | {leaf} | 4 | 103 |
| 6 | {leaf} | 5 | 184 |
| 7 | {leaf} | 6 | 145 |
| 8 | {leaf} | 7 | 115 |
nine pages: the root (page 0, no flags) and eight leaves, linked right to left by rightlink the way they were split off. the leaves hold between 79 and 184 points each: GiST doesn't aim for even pages, it aims for tight boxes.
SELECT itemoffset, ctid, keys
FROM gist_page_items(get_raw_page('pts_gist', 0), 'pts_gist')
ORDER BY itemoffset;| itemoffsetint2 | ctidtid | keystext |
|---|---|---|
| 1 | (1,65535) | (p)=("(37,42),(0,0)") |
| 2 | (2,65535) | (p)=("(37,72),(0,44)") |
| 3 | (3,65535) | (p)=("(31,99),(0,74)") |
| 4 | (4,65535) | (p)=("(67,29),(38,0)") |
| 5 | (5,65535) | (p)=("(99,29),(69,0)") |
| 6 | (6,65535) | (p)=("(99,63),(38,30)") |
| 7 | (7,65535) | (p)=("(69,99),(32,64)") |
| 8 | (8,65535) | (p)=("(99,99),(71,54)") |
- ├── (0,0)–(37,42) → page 1176 points
- ├── (0,44)–(37,72) → page 2113 points
- ├── (0,74)–(31,99) → page 379 points
- ├── (38,0)–(67,29) → page 485 points
- ├── (69,0)–(99,29) → page 5103 points
- ├── (38,30)–(99,63) → page 6184 points
- ├── (32,64)–(69,99) → page 7145 points
- └── (71,54)–(99,99) → page 8115 points
each root item is a box, written as (upper right), (lower left), and a downlink in ctid (the 65535 offset marks a downlink, not a row). leaf 7, (69,99),(32,64), and leaf 2, (37,72),(0,44), overlap in a small rectangle around (34, 68): a search there has to read both.
SELECT itemoffset, ctid, keys
FROM gist_page_items(get_raw_page('pts_gist', 1), 'pts_gist')
ORDER BY itemoffset
LIMIT 4;| itemoffsetint2 | ctidtid | keystext |
|---|---|---|
| 1 | (2,148) | (p)=("(24,0),(24,0)") |
| 2 | (0,4) | (p)=("(33,0),(33,0)") |
| 3 | (3,8) | (p)=("(6,1),(6,1)") |
| 4 | (0,92) | (p)=("(29,1),(29,1)") |
on a leaf the key is the point itself (a box with both corners equal) and ctid is the row. that's a degenerate box, which is how GiST's point support works: a point is stored as a zero-size box, and every inner key is the box around a page of them.
consistent, penalty, picksplit
GiST is a framework: the tree machinery is generic, and an operator class supplies the geometry. the important methods:
- consistent(entry, query)
- could anything under this entry match? for a box and the query "contained in (40,40)–(45,45)", that's "do they overlap". it may say yes when the answer is no (the box is bigger than its contents), never the reverse; the rows are rechecked at the end.
- union(entries)
- the box around a set of boxes: what the parent stores.
- penalty(entry, new)
- how much a subtree's box would grow to take a new key. an insert goes down the path of least penalty, one page per level, like a b-tree descent.
- picksplit(entries)
- how to divide a full page into two groups with small, little-overlapping boxes. for boxes and points postgres uses a double-sorting split (Korotkov's algorithm, the comment in the source says).
- distance(entry, query)
- the smallest possible distance from the query to anything under the entry. what makes nearest-neighbour search work.
those few functions are why GiST indexes ranges, geometry, PostGIS shapes, ltree paths, trigrams and full-text vectors with the same code. a range index stores the union range of each subtree, and that's what an exclusion constraint (no double booking) searches when it checks a new row for overlaps.
nearest neighbours
SELECT id, p FROM pts ORDER BY p <-> point(50, 50) LIMIT 5;EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, p FROM pts ORDER BY p <-> point(50, 50) LIMIT 5;
SELECT id, p, round((p <-> point(50, 50))::numeric, 2) AS dist
FROM pts ORDER BY p <-> point(50, 50), id LIMIT 5;| idint4 | ppoint | distnumeric |
|---|---|---|
| 319 | (51,49) | 1.41 |
| 828 | (49,48) | 2.24 |
| 370 | (48,48) | 2.83 |
| 125 | (48,47) | 3.61 |
| 955 | (50,54) | 4.00 |
Order By: (p <-> '(50,50)'::point) is the sign: the index returns rows already in distance order, and the Limit stops after five. 7 buffers in all, for an index of 9 pages plus the table's: the root, the leaves whose boxes come close to (50, 50), and the heap pages of five rows. this is the same "best first" search that vector indexes do approximately on embeddings; here it's exact.
SP-GiST: partitions that don't overlap
GiST's boxes can overlap, so a search can go down several paths. SP-GiST ("space-partitioned") splits space so that pieces never overlap: each inner node divides its region into fixed parts, a quadtree into four quadrants around a centre point, a k-d tree into two halves along alternating axes, a radix tree by the next characters of a string. a node's children can have different depths, so the tree is unbalanced, and postgres packs several nodes into each page to keep lookups few pages deep.
CREATE INDEX pts_spgist ON pts USING spgist (p);
DROP INDEX pts_gist;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, p FROM pts ORDER BY p <-> point(50, 50) LIMIT 5;
EXPLAIN (COSTS OFF) SELECT id FROM pts WHERE p <@ box '((40,40),(45,45))';the same nearest-neighbour plan works on SP-GiST pg 12+, and so does containment. it read 14 buffers to GiST's 7 here, on a tiny table; which one wins depends on the data. SP-GiST shines when the data partitions cleanly: text prefixes (LIKE 'abc%' with text_ops, and ^@), IP addresses (inet_ops), points spread unevenly. GiST is the general one, and the only one of the two that handles overlapping shapes (boxes, polygons, ranges that overlap) without duplicating them.
keylines
- GiST inner entries are bounding boxes (predicates) covering their subtree; boxes may overlap.
- consistent, union, penalty, picksplit and distance are all an operator class has to supply.
- searching visits every subtree whose box is consistent with the query, maybe several per level.
- SP-GiST partitions space into non-overlapping parts: quadtrees, k-d trees, radix trees.
- both serve
ORDER BY … <-> … LIMITas a best-first scan: no sort, far pages never read.