Algorithm Search⌘K

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
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 (p,ptr)(p, ptr) says that pp holds for every record below ptrptr. 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 qq.
  • 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 E=(p,ptr)E = (p, ptr) an entry and PP a set of entries:

method what it does
Consistent(E,q)(E, q) false only if p∧qp \wedge q cannot hold; true otherwise, so false positives are allowed
Union(P)(P) a predicate that holds for every record below any entry of PP
Compress(E)(E) an entry with a shorter representation p′p', where pp implies p′p'
Decompress(E)(E) the inverse of Compress, again possibly a weaker predicate
Penalty(E1,E2)(E_1, E_2) the cost of putting E2E_2 below E1E_1, used to choose the subtree
PickSplit(P)(P) split M+1M + 1 entries into two sets of at least mm entries each

Representation

The tree has these properties, which are the tree properties of the paper:

  1. Every node other than the root has between mm and MM entries, with 2≤m≤(M+1)/22 \le m \le (M + 1) / 2. The root has at least two entries unless it is a leaf.
  2. A leaf entry is (p,rid)(p, rid), where pp holds for the key of the record ridrid (exactly, or as a weaker predicate if Compress is lossy).
  3. An index entry is (p,ptr)(p, ptr), where pp holds for every record reachable from ptrptr. The predicates of two entries in one node may overlap.
  4. 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

  1. SEARCH(R, q) ▷ R is a node, q a query predicate
  2. 1if R is not a leaf then
  3. 2for each entry (p, ptr) of R do
  4. 3if CONSISTENT(DECOMPRESS(p), q) then SEARCH(ptr, q)
  5. 4else for each entry (p, rid) of R do
  6. 5if CONSISTENT(DECOMPRESS(p), q) then output rid
  7. INSERT(T, E) ▷ E = (key, rid)
  8. 6L ← CHOOSE-SUBTREE(root of T, E)
  9. 7add (COMPRESS(key), rid) to L
  10. 8if L has more than M entries then SPLIT(L)
  11. 9ADJUST-KEYS from L up to the root
  12. CHOOSE-SUBTREE(R, E)
  13. 10if R is a leaf then return R
  14. 11F ← the entry of R with the least PENALTY(F, E)
  15. 12return CHOOSE-SUBTREE(F.ptr, E)
  16. SPLIT(N) ▷ N has M + 1 entries
  17. 13(P1, P2) ← PICKSPLIT(the entries of N)
  18. 14N keeps P1; a new node N' gets P2
  19. 15add (COMPRESS(UNION(P2)), N') to the parent of N; split the parent if it is now full
  20. 16set the key of N in its parent to COMPRESS(UNION(P1))
  21. DELETE(T, rid)
  22. 17find the leaf that holds rid by a search with the key of rid; remove the entry
  23. 18for each node on the path with fewer than m entries: remove it and keep its records to reinsert
  24. 19ADJUST-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 [lo,hi][lo, hi], and a point xx is [x,x][x, x]. Consistent is "overlaps the query range", Union is the smallest covering interval, Penalty is the growth in length, and PickSplit sorts by lolo 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 M=4M = 4 and m=2m = 2.

  1. 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 [10,20][10, 20] and [30,80][30, 80].
  2. For 60, the penalties are 60−10−10=4060 - 10 - 10 = 40 for [10,20][10, 20] and 0 for [30,80][30, 80], 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}.
  3. 40 goes into [30,50][30, 50] with penalty 0, and 70 into [60,90][60, 90].

The final root has the keys [10,20][10, 20], [30,50][30, 50] and [60,90][60, 90], over the leaves {10, 20}, {30, 40, 50} and {60, 70, 80, 90}. The query "overlaps [25,45][25, 45]" calls Consistent on the three root keys, and only [30,50][30, 50] passes. The search reads 2 nodes and returns 30 and 40.

Rectangles. Insert a=(0,0,2,2)a = (0,0,2,2), b=(1,6,3,8)b = (1,6,3,8), c=(7,1,9,3)c = (7,1,9,3), d=(6,7,8,9)d = (6,7,8,9), e=(2,2,4,4)e = (2,2,4,4) and f=(8,8,9,9)f = (8,8,9,9), written as (x1,y1,x2,y2)(x_1, y_1, x_2, y_2), with M=4M = 4 and m=2m = 2. 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 (0,0,4,8)(0,0,4,8) over a,b,ea, b, e and (6,1,9,9)(6,1,9,9) over c,d,fc, d, f. The query rectangle (3,3,7,7)(3,3,7,7) meets both root keys, which overlap it, so the search reads all 3 nodes and returns b,c,d,eb, c, d, e. 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 rr matches qq, then by property 3 every key on the path from the root to rr holds for rr, so its conjunction with qq 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 mm 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 pp and a record key kk, "pp covers kk" means that pp holds for kk. The extension must satisfy these contracts, which are the contracts of the paper:

  • (C1) If pp covers some kk that satisfies the query qq, then Consistent(p,q)(p, q) is true.
  • (C2) Union(P)(P) covers every record key that some key of PP covers.
  • (C3) Compress(p)(p) covers every record key that pp covers, and Decompress(p)(p) covers every record key that pp covers.
  • (C4) PickSplit on M+1M + 1 entries returns two sets of at least mm 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 ⌊(M+1)/2⌋≥m\lfloor (M+1)/2 \rfloor \ge m entries, and the quadratic split gives the rest of the entries to a group as soon as that group needs them to reach mm.

Invariant. (P1) Every node other than the root has between mm and MM entries; an inner root has at least two. (P2) Every leaf entry (p,rid)(p, rid) has a key pp that covers the key of record ridrid. (P3) Every index entry (p,ptr)(p, ptr) has $p = $ Compress(Union(the decompressed keys of ptrptr)). (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 rr covers the key of rr.

Proof. By induction from the leaf up. The leaf entry covers rr by (P2). If an entry of node vv covers rr, then the key of vv in its parent is Compress(Union(...)) of a set that includes that entry, so it covers rr by (C2) and (C3). □\square

Claim 1 (search). If the invariant holds, SEARCH(root,q)(root, q) outputs every record whose key satisfies qq, and with an exact extension it outputs no other record. The recheck in search makes the result exact for a lossy extension.

Proof. Let rr satisfy qq. By Lemma 1 every key on the path to rr covers the key of rr, which satisfies qq, 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 rr. If Compress and Decompress are the identity, the leaf key is the exact key of rr, 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 qq. □\square

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 M+1M + 1 entries, L13 and L14 split it into two nodes with at least mm and at most M+1−m≤MM + 1 - m \le M 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. □\square

Claim 3 (delete). DELETE keeps the invariant and removes exactly the record ridrid.

Proof. By Lemma 1 and (C1), the search for the leaf at L17 with the exact key of ridrid reaches the leaf entry of ridrid, because Consistent(p,k)(p, k) is true when pp covers kk. Removing the entry keeps (P2) for the others. Walking up, a node with fewer than mm 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 ridrid is in the tree at the end. □\square

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 mm entries, so the height hh is at most 1+⌈log⁡m(n/m)⌉1 + \lceil \log_m (n / m) \rceil, and h=O(log⁡mn)h = O(\log_m n).
  • Search. If at most one entry per node is consistent with qq, as with disjoint intervals and a point query, a search reads hh pages and makes O(hM)O(h M) Consistent calls. In the worst case every key overlaps qq and the search reads every node, O(n/m)O(n / m) 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 hh pages to choose a leaf, with MM Penalty calls per level, and writes up to h+1h + 1 pages for the splits and the key changes. The quadratic PickSplit costs O(M2)O(M^2) 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 mm 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.

generalized_search_tree.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of io.average
  • a full proof of io.best
  • a full proof of io.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/SE99CH/text.yaml