skip to content

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:

12345678
real output, postgres 18.6 (PGlite 0.5.12) · the run blocks below
1,000 points (the table's rows) and the bounding boxes on the GiST root page, read with gist_page_items. each box covers one leaf page. the boxes tile the square roughly, with gaps and a little overlap. the five nearest points to (50, 50) are hot.

read it yourself

pageinspect reads GiST pages pg 14+:

sqlempty db · ext=pageinspect · session gs
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;
output, from postgres 18.6
#1 · SELECT 1000
#2 · CREATE INDEX
#3 · SELECT 9
blknoint8flagstext[]rightlinkint8itemsint8
0{}42949672958
1{leaf}4294967295176
2{leaf}1113
3{leaf}279
4{leaf}385
5{leaf}4103
6{leaf}5184
7{leaf}6145
8{leaf}7115
(9 rows)

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.

sqlempty db · ext=pageinspect · session gs
continues session gs (1 earlier block run first)
SELECT itemoffset, ctid, keys
FROM gist_page_items(get_raw_page('pts_gist', 0), 'pts_gist')
ORDER BY itemoffset;
output, from postgres 18.6
SELECT 8
itemoffsetint2ctidtidkeystext
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)")
(8 rows)
  • ├── (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
the whole index as a tree, from the two blocks above: one root page of eight boxes, each the bounding box of one leaf page of 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.

sqlempty db · ext=pageinspect · session gs
continues session gs (2 earlier blocks run first)
SELECT itemoffset, ctid, keys
FROM gist_page_items(get_raw_page('pts_gist', 1), 'pts_gist')
ORDER BY itemoffset
LIMIT 4;
output, from postgres 18.6
SELECT 4
itemoffsetint2ctidtidkeystext
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)")
(4 rows)

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

predict the output
ORDER BY p <-> point(50, 50) LIMIT 5 on 1,000 points with a GiST index. how many pages does the index scan read?
sql
SELECT id, p FROM pts ORDER BY p <-> point(50, 50) LIMIT 5;
sqlempty db · ext=pageinspect · session gs
continues session gs (3 earlier blocks run first)
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;
output, from postgres 18.6
#1 · EXPLAIN
Limit (actual rows=5.00 loops=1) Buffers: shared hit=7 -> Index Scan using pts_gist on pts (actual rows=5.00 loops=1) Order By: (p <-> '(50,50)'::point) Index Searches: 1 Buffers: shared hit=7 Planning: Buffers: shared hit=21 read=3
#2 · SELECT 5
idint4ppointdistnumeric
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
(5 rows)

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.

model of a point quadtree over the same 1,000 rows, not read from the index
the same 1,000 rows partitioned the way a point quadtree does it: each square split into four at its centre until it holds at most 64 points. squares never overlap, so a point belongs to exactly one, and dense areas get deeper. this is a model of the idea, not the index's real nodes: SP-GiST's quad_point_ops picks its own centres, and pageinspect can't read SP-GiST.
sqlempty db · ext=pageinspect · session gs
continues session gs (4 earlier blocks run first)
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))';
output, from postgres 18.6
#1 · CREATE INDEX
#2 · DROP INDEX
#3 · EXPLAIN
Limit (actual rows=5.00 loops=1) Buffers: shared hit=14 -> Index Scan using pts_spgist on pts (actual rows=5.00 loops=1) Order By: (p <-> '(50,50)'::point) Index Searches: 1 Buffers: shared hit=14 Planning: Buffers: shared hit=20
#4 · EXPLAIN
Index Scan using pts_spgist on pts Index Cond: (p <@ '(45,45),(40,40)'::box)

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 … <-> … LIMIT as a best-first scan: no sort, far pages never read.