Data structureadvanced
Generalized search tree (GiST)
Also called GiST.
A balanced tree template whose keys are predicates. Six key methods (Consistent, Union, Compress, Decompress, Penalty, PickSplit) turn it into a B+ tree, an R-tree or other indexes.
- Time
- O(n) worstO(h M) average · best
- Space
- O(n) extra
- Counts
- io O(n / m) worstio O(log_m n) average · best
- Where
- M = the largest number of entries in a node; h = the height of the tree; m = the smallest number of entries in a node other than the root; n = the number of records
- Properties
- deterministicexactexternalnot in placeonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joseph M. Hellerstein, Jeffrey F. Naughton, Avi Pfeffer, 1995
A generalized search tree (GiST) is a balanced tree of pages in which every key is a predicate: an index entry says that holds for every record below . The tree code for search, insert and delete is written once. An index designer supplies six key methods that say what a predicate is, when it can match a query, how predicates combine, and how to split a full node. With interval predicates the tree behaves like a B+ tree, and with bounding boxes it behaves like an R-tree; the GiST is the template that both are instances of.
In plain words
Picture a set of boxes inside boxes. Each box has a label that is true of everything inside it, such as "numbers from 30 to 50" or "points inside this rectangle". To find things, you open only the boxes whose label could match your question. To put a thing away, you choose the box whose label has to change the least, and when a box gets too full, you split its contents into two boxes and write a new label on each.
A B+ tree and an R-tree both work like this. They differ only in what a label is, how two labels combine, how to measure "change the least", and how to split. A GiST lets you write just those four things, plus two more that pack a label into less space, and it does the rest.
The abstract type
A GiST holds a set of records, each with a key from a domain chosen by the extension, and answers queries that are predicates over that domain.
search(T, q): every record whose key is consistent with .insert(T, key, rid): add a record.delete(T, rid): remove a record.
The kinds of query depend on the extension: an overlap with a range for the B+ tree instance, an intersection with a rectangle for the R-tree instance, and containment of elements for the RD-tree instance of the paper, which indexes sets.
The six key methods, as in the paper, with an entry and a set of entries:
| method | what it does |
|---|---|
| Consistent | false only if cannot hold; true otherwise, so false positives are allowed |
| Union | a predicate that holds for every record below any entry of |
| Compress | an entry with a shorter representation , where implies |
| Decompress | the inverse of Compress, again possibly a weaker predicate |
| Penalty | the cost of putting below , used to choose the subtree |
| PickSplit | split entries into two sets of at least entries each |
Representation
The tree has these properties, which are the tree properties of the paper:
- Every node other than the root has between and entries, with . The root has at least two entries unless it is a leaf.
- A leaf entry is , where holds for the key of the record (exactly, or as a weaker predicate if Compress is lossy).
- An index entry is , where holds for every record reachable from . The predicates of two entries in one node may overlap.
- All leaves are at the same level.
Property 3 is weaker than the separator rule of a B+ tree: a key does not tell a search where a record is, only where it may be. This is what makes the template general, and it is also why a search may have to follow more than one path.
Operations
SEARCH(R, q) ▷ R is a node, q a query predicate- 1
if R is not a leaf then - 2
for each entry (p, ptr) of R do - 3
if CONSISTENT(DECOMPRESS(p), q) then SEARCH(ptr, q) - 4
else for each entry (p, rid) of R do - 5
if CONSISTENT(DECOMPRESS(p), q) then output rid INSERT(T, E) ▷ E = (key, rid)- 6
L ← CHOOSE-SUBTREE(root of T, E) - 7
add (COMPRESS(key), rid) to L - 8
if L has more than M entries then SPLIT(L) - 9
ADJUST-KEYS from L up to the root CHOOSE-SUBTREE(R, E)- 10
if R is a leaf then return R - 11
F ← the entry of R with the least PENALTY(F, E) - 12
return CHOOSE-SUBTREE(F.ptr, E) SPLIT(N) ▷ N has M + 1 entries- 13
(P1, P2) ← PICKSPLIT(the entries of N) - 14
N keeps P1; a new node N' gets P2 - 15
add (COMPRESS(UNION(P2)), N') to the parent of N; split the parent if it is now full - 16
set the key of N in its parent to COMPRESS(UNION(P1)) DELETE(T, rid)- 17
find the leaf that holds rid by a search with the key of rid; remove the entry - 18
for each node on the path with fewer than m entries: remove it and keep its records to reinsert - 19
ADJUST-KEYS on the path, then reinsert the kept records with INSERT
ADJUST-KEYS sets the key of each node on the path to COMPRESS(UNION) of the keys of its entries, which keeps property 3 and keeps the keys tight. If the root splits, a new root with two entries is made. If the root of an inner tree ends with one entry, its child becomes the root.
Instances. The code on this page has two extensions:
- Intervals (like a B+ tree): a key is an integer interval , and a point is . Consistent is "overlaps the query range", Union is the smallest covering interval, Penalty is the growth in length, and PickSplit sorts by and cuts in half. Compress is the identity.
- Rectangles (like an R-tree): Consistent is "intersects", Union is the bounding box, Penalty is the growth in area with the area as a tie break (Guttman's rule), and PickSplit is Guttman's quadratic split. Compress can round each rectangle outward to a grid, which needs fewer bits and gives a weaker predicate.
For linearly ordered keys, the paper adds methods so that a range search can find the first match and then walk the leaves in order, as a B+ tree does, instead of calling Consistent on every node.
Example
Intervals. Insert the points 50, 20, 80, 10, 30, 60, 90, 40, 70 with and .
- The first four fill the root leaf. The point 30 makes 5 entries, so PickSplit sorts them (10, 20, 30, 50, 80) and splits them into {10, 20} and {30, 50, 80}. The new root has the keys and .
- For 60, the penalties are for and 0 for , so 60 goes right. For 90, the penalties are 70 and 10, and 90 also goes right. That leaf now has 30, 50, 60, 80, 90, and it splits into {30, 50} and {60, 80, 90}.
- 40 goes into with penalty 0, and 70 into .
The final root has the keys , and , over the leaves {10, 20}, {30, 40, 50} and {60, 70, 80, 90}. The query "overlaps " calls Consistent on the three root keys, and only passes. The search reads 2 nodes and returns 30 and 40.
Rectangles. Insert , , , , and , written as , with and . The quadratic split of the first five takes the pair with the most wasted area as seeds, and the tree ends with the root keys over and over . The query rectangle meets both root keys, which overlap it, so the search reads all 3 nodes and returns . This is the price of property 3: overlapping keys can send a search down several paths.
Lossy keys. With rectangles rounded outward to multiples of 8, a test with 100 random rectangles and 40 small queries (seed 9) gives leaf matches that are not real matches. The search then checks each candidate against the stored record, as PostgreSQL does with its "recheck" step.
Correctness
The proofs are in proofs/correctness.md. The main points:
- Search finds every match. If a record matches , then by property 3 every key on the path from the root to holds for , so its conjunction with can hold and Consistent cannot return false. SEARCH follows that path. With a lossy Compress the leaf test can pass for records that do not match, so the result is a superset that a recheck makes exact.
- Insert and delete keep the properties. ADJUST-KEYS makes each key the Union of its child, which implies every key below it. PickSplit returns two sets of at least entries. Splits and reinsertion keep all leaves at one level, because a split adds a node at the same level and only a root split adds a level.
- Termination. Every call descends one level, and the height is finite.
Proof: A GiST search returns every matching record, and insert and delete keep the tree propertiesfull
We use the notation of the page. A key is a predicate on the key domain. For a key and a record key , " covers " means that holds for . The extension must satisfy these contracts, which are the contracts of the paper:
- (C1) If covers some that satisfies the query , then Consistent is true.
- (C2) Union covers every record key that some key of covers.
- (C3) Compress covers every record key that covers, and Decompress covers every record key that covers.
- (C4) PickSplit on entries returns two sets of at least entries each.
The interval and rectangle extensions of the code satisfy these: Consistent is the exact overlap or intersection test, so (C1) holds; Union is the smallest covering interval or box; Compress is the identity, or rounds a box outward, which only makes it larger; the sorted halves have entries, and the quadratic split gives the rest of the entries to a group as soon as that group needs them to reach .
Invariant. (P1) Every node other than the root has between and entries; an inner root has at least two. (P2) Every leaf entry has a key that covers the key of record . (P3) Every index entry has $p = $ Compress(Union(the decompressed keys of )). (P4) All leaves are at the same depth.
Lemma 1 (cover). If (P2) and (P3) hold, then every key on the path from the root to the leaf entry of a record covers the key of .
Proof. By induction from the leaf up. The leaf entry covers by (P2). If an entry of node covers , then the key of in its parent is Compress(Union(...)) of a set that includes that entry, so it covers by (C2) and (C3).
Claim 1 (search). If the invariant holds, SEARCH outputs every record whose key satisfies , and with an exact extension it outputs no other record. The recheck in search makes the result exact for a lossy extension.
Proof. Let satisfy . By Lemma 1 every key on the path to covers the key of , which satisfies , so by (C1) Consistent is true on the decompressed key at every step of the path. So L3 descends along the path and L5 outputs . If Compress and Decompress are the identity, the leaf key is the exact key of , and Consistent is the exact test, so L5 outputs only matches. If they are lossy, L5 may output extra records, and the recheck removes exactly the records whose stored key does not satisfy .
Claim 2 (insert). INSERT keeps the invariant.
Proof. CHOOSE-SUBTREE descends to a leaf, and L7 adds a leaf entry with Compress(key), which covers the key by (C3), so (P2) holds. If the leaf has entries, L13 and L14 split it into two nodes with at least and at most entries each, by (C4), which gives (P1) for both. Both are at the depth of the old leaf, so (P4) holds. L15 and L16 set the parent keys of both nodes to Compress(Union(...)) of their entries, which is (P3). The parent now has one more entry, and the same argument applies to it if it overflows. The walk upward (L9) recomputes the key of every node on the path, so (P3) holds for every entry whose subtree changed, and the other entries are unchanged. If the root splits, the new root has the two halves as entries, with keys as in (P3); every leaf is now one level deeper, so (P4) still holds.
Claim 3 (delete). DELETE keeps the invariant and removes exactly the record .
Proof. By Lemma 1 and (C1), the search for the leaf at L17 with the exact key of reaches the leaf entry of , because Consistent is true when covers . Removing the entry keeps (P2) for the others. Walking up, a node with fewer than entries is removed from its parent, and the records in its subtree are kept; a node that stays has its key recomputed (L19), which keeps (P3). Removing whole subtrees does not change the depth of any leaf that stays, so (P4) holds. If the root is an inner node with one entry, its child becomes the root, and every leaf depth drops by one. Every kept record is inserted again by INSERT, which keeps the invariant by Claim 2, and so every record other than is in the tree at the end.
Termination. CHOOSE-SUBTREE and SEARCH go down one level per call, and the height is finite. The walk upward in INSERT and DELETE goes up one level per step. Each reinsertion in DELETE is an INSERT, which does not reinsert anything, so DELETE ends.
The tests check the invariant with check (the fill bounds, the leaf depths, (P2), (P3) and the cover of Lemma 1) during random inserts and deletes, and compare every search with a scan of all records for both extensions, with exact and with lossy keys.
Complexity
Costs are in the page I/O model: one node is one page. In the external memory model, the memory holds M/B blocks; this page counts page reads only and does not use a buffer size. On this page, M and m count the entries in a node.
- Height. Every node other than the root has at least entries, so the height is at most , and .
- Search. If at most one entry per node is consistent with , as with disjoint intervals and a point query, a search reads pages and makes Consistent calls. In the worst case every key overlaps and the search reads every node, pages. How close a GiST gets to the good case depends on Penalty and PickSplit; this is a property of the extension, not a guarantee of the template.
- Insert reads pages to choose a leaf, with Penalty calls per level, and writes up to pages for the splits and the key changes. The quadratic PickSplit costs area computations per split.
- Delete costs one search, which can visit several paths, plus the reinsertion of the records of the removed nodes.
Variants
- Concurrency and recovery. Kornacker, Mohan and Hellerstein (1997) add a right link to each node and a node sequence number, as in the B-link tree, so that a search that reads a node during a split can detect the split and follow the right link. The keys of a GiST are not ordered, so the B-link rule of comparing with a high key does not work, and the sequence number replaces it.
- RD-tree. The paper's third instance indexes sets: a key is a set that contains all sets below it, and Compress can store it in a lossy form such as a signature.
- Nearest neighbor search. Later work runs a best-first search on the same tree with a distance bound per key, which gives nearest neighbor queries for any extension that can bound a distance.
- Space-partitioning trees. A GiST keeps balance and lets keys overlap. SP-GiST, a related template, covers trees that split space without overlap, such as the kd-tree and the quadtree.
When to use it
Use a GiST when a database must index a new kind of data (geometric shapes, ranges, sets, text signatures, network addresses) and the designer wants the system's existing page handling, concurrency and logging, not a new access method. PostgreSQL ships a GiST framework, and its range, geometric and full-text operator classes are GiST extensions. For plain ordered keys, a native B+ tree is simpler and faster, because it can use separators and in-order leaf scans.
Pitfalls
- A Consistent that is too strict. Consistent may return true when the answer is "maybe", but never false when a match is possible. An exact-looking test on a lossy compressed key loses records.
- A Union that is not a cover. If Union does not imply the keys of all its entries, property 3 fails and searches miss records. This also holds after Decompress: Union must cover the decompressed keys.
- No recheck with a lossy Compress. The leaf test on a compressed key is only a filter. Without a recheck, the result has false positives.
- A PickSplit that ignores the minimum fill. Every split must leave at least entries on each side, or the height bound fails and deletes underflow at once.
- A Penalty that ignores overlap. If Penalty lets keys of one node overlap a lot, every search follows many paths and the tree degrades to a scan.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-search-tree/. The authors are listed in prov/SE99CH.jsonl.
"""Generalized search tree (GiST) of Hellerstein, Naughton and Pfeffer (1995).
The tree code knows nothing about keys. An extension object supplies the six
key methods: consistent, union, compress, decompress, penalty and pick_split.
Two extensions are given: IntervalExt (it behaves like a B+ tree on integers)
and RectExt (it behaves like an R-tree with Guttman's quadratic split, and its
compress step rounds rectangles outward to a grid, so its keys are lossy).
A leaf entry is (compressed key, record id). The exact key of each record is
kept in self.records, so that a search on lossy keys can recheck its result.
"""
from typing import Dict, List, Optional, Sequence, Tuple
class Entry:
__slots__ = ("key", "ptr")
def __init__(self, key, ptr):
self.key = key # a compressed predicate
self.ptr = ptr # a Node, or a record id in a leaf
class Node:
__slots__ = ("leaf", "entries", "parent")
def __init__(self, leaf: bool):
self.leaf = leaf
self.entries: List[Entry] = []
self.parent: Optional["Node"] = None
class IntervalExt:
"""Keys are closed integer intervals (lo, hi); a point x is (x, x).
A query (a, b) asks for the keys that overlap [a, b].
"""
lossy = False
def consistent(self, p, q) -> bool:
return p[0] <= q[1] and q[0] <= p[1]
def union(self, ps: Sequence) -> Tuple[int, int]:
return (min(p[0] for p in ps), max(p[1] for p in ps))
def compress(self, p):
return p
def decompress(self, p):
return p
def penalty(self, p, new) -> int:
"""How much p must grow to cover new."""
return (max(p[1], new[1]) - min(p[0], new[0])) - (p[1] - p[0])
def pick_split(self, ps: Sequence, m: int) -> Tuple[List[int], List[int]]:
order = sorted(range(len(ps)), key=lambda i: (ps[i][0], ps[i][1], i))
half = len(ps) // 2
return order[:half], order[half:]
def contains(self, p, k) -> bool:
return p[0] <= k[0] and k[1] <= p[1]
def _area(r) -> int:
return (r[2] - r[0] + 1) * (r[3] - r[1] + 1)
def _bbox(a, b):
return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
class RectExt:
"""Keys are integer rectangles (x1, y1, x2, y2), corners included.
A query rectangle asks for the keys that intersect it. With grid > 1,
compress rounds a rectangle outward to multiples of grid, so a compressed
key covers more than the record and the search must recheck.
"""
def __init__(self, grid: int = 1):
self.grid = grid
self.lossy = grid > 1
def consistent(self, p, q) -> bool:
return p[0] <= q[2] and q[0] <= p[2] and p[1] <= q[3] and q[1] <= p[3]
def union(self, ps: Sequence):
r = ps[0]
for p in ps[1:]:
r = _bbox(r, p)
return r
def compress(self, p):
g = self.grid
return (p[0] - p[0] % g, p[1] - p[1] % g, p[2] + (g - 1 - p[2] % g), p[3] + (g - 1 - p[3] % g))
def decompress(self, p):
return p
def penalty(self, p, new):
"""Guttman's rule: the growth in area, and then the area."""
return (_area(_bbox(p, new)) - _area(p), _area(p))
def pick_split(self, ps: Sequence, m: int) -> Tuple[List[int], List[int]]:
"""Guttman's quadratic split."""
n = len(ps)
best = None
for i in range(n):
for j in range(i + 1, n):
waste = _area(_bbox(ps[i], ps[j])) - _area(ps[i]) - _area(ps[j])
if best is None or waste > best[0]:
best = (waste, i, j)
_, i, j = best
g1, g2 = [i], [j]
b1, b2 = ps[i], ps[j]
rest = [t for t in range(n) if t != i and t != j]
while rest:
if len(g1) + len(rest) == m:
g1.extend(rest)
break
if len(g2) + len(rest) == m:
g2.extend(rest)
break
pick = max(rest, key=lambda t: (abs((_area(_bbox(b1, ps[t])) - _area(b1))
- (_area(_bbox(b2, ps[t])) - _area(b2))), -t))
rest.remove(pick)
d1 = _area(_bbox(b1, ps[pick])) - _area(b1)
d2 = _area(_bbox(b2, ps[pick])) - _area(b2)
if (d1, _area(b1), len(g1)) <= (d2, _area(b2), len(g2)):
g1.append(pick)
b1 = _bbox(b1, ps[pick])
else:
g2.append(pick)
b2 = _bbox(b2, ps[pick])
return g1, g2
def contains(self, p, k) -> bool:
return p[0] <= k[0] and p[1] <= k[1] and k[2] <= p[2] and k[3] <= p[3]
class GiST:
def __init__(self, ext, max_entries: int = 4, min_entries: int = 2):
if not 2 <= min_entries <= (max_entries + 1) // 2:
raise ValueError("need 2 <= min_entries <= (max_entries + 1) / 2")
self.ext = ext
self.M = max_entries
self.m = min_entries
self.root = Node(True)
self.records: Dict[object, object] = {}
self.visited = 0
# ----- search -----
def search(self, q) -> List:
"""SEARCH: the record ids whose keys are consistent with q, sorted."""
out: List = []
self.visited = 0
self._search(self.root, q, out)
if self.ext.lossy:
out = [r for r in out if self.ext.consistent(self.records[r], q)]
return sorted(out)
def _search(self, node: Node, q, out: List) -> None:
self.visited += 1
if not node.leaf: # @line L1
for e in node.entries: # @line L2
if self.ext.consistent(self.ext.decompress(e.key), q): # @line L3
self._search(e.ptr, q, out) # @line L3
else:
for e in node.entries: # @line L4
if self.ext.consistent(self.ext.decompress(e.key), q): # @line L5
out.append(e.ptr) # @line L5
# ----- insert -----
def insert(self, key, rid) -> None:
if rid in self.records:
raise KeyError("record id already present")
self.records[rid] = key
leaf = self._choose_subtree(self.root, key) # @line L6
leaf.entries.append(Entry(self.ext.compress(key), rid)) # @line L7
self._fix_upward(leaf) # @line L8
def _choose_subtree(self, node: Node, key) -> Node:
while not node.leaf: # @line L10
best = min(range(len(node.entries)), # @line L11
key=lambda i: (self.ext.penalty(self.ext.decompress(node.entries[i].key), key), i))
node = node.entries[best].ptr # @line L12
return node # @line L10
def _node_key(self, node: Node):
"""COMPRESS(UNION(the keys of the entries of node))."""
return self.ext.compress(self.ext.union([self.ext.decompress(e.key) for e in node.entries]))
def _entry_of(self, node: Node) -> Entry:
for e in node.parent.entries:
if e.ptr is node:
return e
raise AssertionError("node not found in its parent")
def _split(self, node: Node) -> Node:
keys = [self.ext.decompress(e.key) for e in node.entries]
g1, g2 = self.ext.pick_split(keys, self.m) # @line L13
assert len(g1) >= self.m and len(g2) >= self.m
old = node.entries
node.entries = [old[i] for i in sorted(g1)] # @line L14
other = Node(node.leaf) # @line L14
other.entries = [old[i] for i in sorted(g2)] # @line L14
if not other.leaf:
for e in other.entries:
e.ptr.parent = other
return other
def _fix_upward(self, node: Node) -> None:
"""Split nodes that overflow and ADJUST-KEYS up to the root."""
while True:
new = self._split(node) if len(node.entries) > self.M else None # @line L8
if node.parent is None:
if new is not None:
root = Node(False)
for c in (node, new):
c.parent = root
root.entries.append(Entry(self._node_key(c), c))
self.root = root
return
parent = node.parent
self._entry_of(node).key = self._node_key(node) # @line L16
if new is not None:
new.parent = parent
parent.entries.append(Entry(self._node_key(new), new)) # @line L15
node = parent # @line L9
# ----- delete -----
def delete(self, rid) -> bool:
"""DELETE: remove a record; condense underfull nodes by reinsertion."""
if rid not in self.records:
return False
key = self.records.pop(rid)
leaf = self._find_leaf(self.root, key, rid) # @line L17
assert leaf is not None
leaf.entries = [e for e in leaf.entries if e.ptr != rid] # @line L17
orphans: List = []
node = leaf
while node.parent is not None:
parent = node.parent
if len(node.entries) < self.m: # @line L18
parent.entries = [e for e in parent.entries if e.ptr is not node]
self._collect(node, orphans)
elif node.entries:
self._entry_of(node).key = self._node_key(node) # @line L19
node = parent
while not self.root.leaf and len(self.root.entries) == 1:
self.root = self.root.entries[0].ptr
self.root.parent = None
if not self.root.leaf and not self.root.entries:
self.root = Node(True)
for r in orphans: # @line L18
k = self.records.pop(r)
self.insert(k, r)
return True
def _find_leaf(self, node: Node, key, rid) -> Optional[Node]:
for e in node.entries:
if node.leaf:
if e.ptr == rid:
return node
elif self.ext.consistent(self.ext.decompress(e.key), key):
found = self._find_leaf(e.ptr, key, rid)
if found is not None:
return found
return None
def _collect(self, node: Node, out: List) -> None:
for e in node.entries:
if node.leaf:
out.append(e.ptr)
else:
self._collect(e.ptr, out)
# ----- checks -----
def height(self) -> int:
h, v = 1, self.root
while not v.leaf:
h, v = h + 1, v.entries[0].ptr
return h
def check(self) -> None:
"""Raise AssertionError if a tree property of the paper fails."""
depths = set()
rids: List = []
self._check(self.root, 1, depths, rids)
assert len(depths) <= 1, "leaves at different depths"
assert sorted(rids, key=repr) == sorted(self.records, key=repr)
def _check(self, node: Node, depth: int, depths, rids) -> List:
if node is not self.root:
assert self.m <= len(node.entries) <= self.M, "fill out of range"
else:
assert len(node.entries) <= self.M
if not node.leaf:
assert len(node.entries) >= 2
if node.leaf:
depths.add(depth)
keys = []
for e in node.entries:
rids.append(e.ptr)
exact = self.records[e.ptr]
assert self.ext.contains(self.ext.decompress(e.key), exact)
keys.append(exact)
return keys
below_all = []
for e in node.entries:
assert e.ptr.parent is node
assert e.key == self._node_key(e.ptr), "key is not the union of its child"
below = self._check(e.ptr, depth + 1, depths, rids)
for k in below:
assert self.ext.contains(self.ext.decompress(e.key), k)
below_all.extend(below)
return below_all
test_generalized_search_tree.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-search-tree/. The authors are listed in prov/SE99CH.jsonl.
import random
import unittest
from generalized_search_tree import GiST, IntervalExt, RectExt
def scan(records, ext, q):
"""The brute force answer: every record whose exact key is consistent with q."""
return sorted(r for r, k in records.items() if ext.consistent(k, q))
def random_interval(rng, span=100, width=6):
a = rng.randrange(span)
return (a, a + rng.randrange(width))
def random_rect(rng, span=60, size=8):
x, y = rng.randrange(span), rng.randrange(span)
return (x, y, x + rng.randrange(size), y + rng.randrange(size))
class TestGiST(unittest.TestCase):
def run_workload(self, ext, make_key, seed, n, M, m):
rng = random.Random(seed)
t = GiST(ext, max_entries=M, min_entries=m)
live = {}
for i in range(n):
k = make_key(rng)
t.insert(k, i)
live[i] = k
if rng.random() < 0.3 and live:
victim = rng.choice(sorted(live))
self.assertTrue(t.delete(victim))
del live[victim]
if i % 25 == 0:
t.check()
t.check()
for _ in range(40):
q = make_key(rng)
self.assertEqual(t.search(q), scan(live, ext, q))
return t, live
def test_interval_instance_like_a_b_plus_tree(self):
for seed in range(6):
self.run_workload(IntervalExt(), random_interval, seed, 150, 4, 2)
self.run_workload(IntervalExt(), lambda r: (lambda x: (x, x))(r.randrange(200)),
seed + 100, 150, 5, 3)
def test_rect_instance_like_an_r_tree(self):
for seed in range(5):
self.run_workload(RectExt(), random_rect, seed, 150, 4, 2)
def test_lossy_compression_needs_the_recheck(self):
ext = RectExt(grid=8)
for seed in range(4):
t, live = self.run_workload(ext, random_rect, seed, 120, 6, 3)
# Without the recheck the leaves give false positives.
rng = random.Random(9)
t = GiST(RectExt(grid=8), 4, 2)
for i in range(100):
t.insert(random_rect(rng), i)
false_pos = 0
for _ in range(40):
q = random_rect(rng, size=3)
raw = []
t._search(t.root, q, raw)
exact = scan(t.records, t.ext, q)
self.assertTrue(set(exact) <= set(raw))
false_pos += len(raw) - len(exact)
self.assertGreater(false_pos, 0)
def test_point_query_prunes(self):
t = GiST(IntervalExt(), 4, 2)
for x in range(64):
t.insert((x, x), x)
t.check()
self.assertEqual(t.search((37, 37)), [37])
self.assertLessEqual(t.visited, 3 * t.height())
self.assertEqual(t.search((10, 13)), [10, 11, 12, 13])
def test_delete_everything(self):
rng = random.Random(3)
t = GiST(RectExt(), 4, 2)
keys = {i: random_rect(rng) for i in range(60)}
for i, k in keys.items():
t.insert(k, i)
order = list(keys)
rng.shuffle(order)
for i in order:
self.assertTrue(t.delete(i))
t.check()
self.assertFalse(t.delete(0))
self.assertEqual(t.search((0, 0, 100, 100)), [])
self.assertTrue(t.root.leaf)
def test_bad_arguments(self):
with self.assertRaises(ValueError):
GiST(IntervalExt(), 4, 3)
t = GiST(IntervalExt(), 4, 2)
t.insert((1, 1), "a")
with self.assertRaises(KeyError):
t.insert((2, 2), "a")
if __name__ == "__main__":
unittest.main()
History
Joseph Hellerstein, Jeffrey Naughton and Avi Pfeffer presented the GiST at VLDB 1995, based on the observation that the B+ tree, the R-tree and many other balanced trees of the time shared their search and update code. They gave the six key methods, the tree methods and three instances. Marcel Kornacker, C. Mohan and Hellerstein added concurrency control and recovery at SIGMOD 1997. The design was built into Postgres, and PostgreSQL still uses it for many of its non-B-tree indexes.
References
- Joseph M. Hellerstein, Jeffrey F. Naughton and Avi Pfeffer, Generalized search trees for database systems, Proceedings of the 21st International Conference on Very Large Data Bases (VLDB 1995), pp. 562 to 573, the tree properties, the six key methods, the tree methods Search, Insert (with ChooseSubtree, Split and AdjustKeys) and Delete, the methods for linearly ordered domains, and the B+ tree, R-tree and RD-tree instances
- Marcel Kornacker, C. Mohan and Joseph M. Hellerstein, Concurrency and recovery in generalized search trees, Proceedings of ACM SIGMOD 1997 (SIGMOD Record 26(2)), pp. 62 to 72, right links and node sequence numbers to detect concurrent splits, and logging of GiST operations
- Antonin Guttman, R-trees, a dynamic index structure for spatial searching, Proceedings of ACM SIGMOD 1984, pp. 47 to 57, the least-enlargement rule for ChooseLeaf and the quadratic split, used here as Penalty and PickSplit of the R-tree instance
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag SE99CH Edit this page History Report an error Markdown