Data structureadvanced
Prefix B-tree
Also called simple prefix B-tree, suffix truncation.
A B+ tree on string keys whose separators are shortest separators, chosen inside a split interval, and whose nodes store keys without the prefix that their fences share.
- Time
- O(L log n) worst · average · best
- Space
- O(n L) extra
- Counts
- io O(log_f n) worst · average · best
- Where
- L = the length of the longest key in characters; d = the half width of the split interval; f = the number of separators that fit in an inner page; n = the number of keys
- Properties
- deterministicexactexternalnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rudolf Bayer, Karl Unterauer, 1977
A prefix B-tree is a B+ tree on string keys that stores less of each key in its inner nodes and in its leaves. Two ideas from Bayer and Unterauer (1977) make it work: a separator in an inner node only has to tell two neighboring subtrees apart, so the shortest string that does this is enough; and all keys between two separators share the prefix of those separators, so a node does not need to store it. Shorter entries give more entries per page, a larger fan-out and a lower tree. Front coding also removes shared prefixes, but it does so in a sorted list that must be decoded from the start of a block, while the prefix B-tree gets the prefix of a node from its two bounding separators during the search.
In plain words
Think of the guide words at the top of a phone book page. The page holds names from "Smart" to "Smith". To send a reader to the right page you do not need the full names. "Smi" is enough to tell "Smart" apart from "Smith", because any name that comes after "Smart" and starts with "Smi" or later belongs to the next page.
Inside a page, every name between the guide words starts with "Sm". So the page can store "art" and "it" and add "Sm" back when it needs the whole name.
The tree does both. Its signposts are as short as they can be, and when a page splits, it looks at a few split points near the middle and takes the one with the shortest signpost.
The abstract type
An ordered set of strings under the usual lexicographic order, with:
contains(T, k): is in ?insert(T, k): add .range(T, lo, hi): the keys with , in order.
Deletes work as in a B+ tree. A separator does not need to change when a key is deleted, because it still separates the two subtrees.
Representation
The tree is a B+ tree: all keys are in the leaves, and every leaf is at the same depth. An inner node with children holds separators . This page uses the convention that every key in is less than and every key in is at least .
- Fences. Each node has two fences, and : the separators to the left and to the right of its pointer in its parent, or the fences of the parent at the ends. The root has the open interval. The invariant is that every key in the subtree of satisfies .
- Shortest separators. When a leaf splits between its keys , the separator is the shortest string with . Bayer and Unterauer call a tree with only this change a simple prefix B-tree.
- Split interval. A split may take any split point within positions of the middle. The node takes the point whose separator is shortest. With the split is the usual one at the middle.
- Stored prefix. Let be the longest common prefix of and (empty if a fence is open). Every key in the subtree of starts with , so stores each key or separator without it. The paper calls the full design, with these prefixes rebuilt during the search, a prefix B-tree.
The capacity of a page is counted in bytes in a real system. The code on this page counts entries to keep the logic short; the savings show up as fewer characters stored.
Operations
SHORTEST-SEPARATOR(a, b) ▷ a < b; the shortest s with a < s ≤ b- 1
i ← 0 - 2
while i < |a| and a[i] = b[i] do i ← i + 1 - 3
return the first i + 1 characters of b SEARCH(T, k)- 4
v ← the root of T - 5
while v is not a leaf do - 6
j ← the number of stored separators of v that are ≤ k without p(v) - 7
v ← child j of v - 8
return whether k without p(v) is a stored key of v SPLIT-LEAF(v) ▷ v has keys k_0 < ... < k_(n-1), one too many- 9
c ← ⌊(n + 1) / 2⌋ - 10
j ← the index in [c - d, c + d] with the shortest SHORTEST-SEPARATOR(k_(j-1), k_j), ties to the one nearest c - 11
s ← SHORTEST-SEPARATOR(k_(j-1), k_j) - 12
left ← k_0 .. k_(j-1); right ← k_j .. k_(n-1) - 13
insert s and a pointer to right into the parent of v, just after the pointer to v - 14
store the keys of left and right without the prefixes of their new fences
Line L3 is well defined. If is a prefix of , the loop stops at . Otherwise it stops at the first position where and differ, and there .
Line L6 strips from . This is safe because the search only enters when , and then starts with .
insert finds the leaf with SEARCH, adds the key, and calls SPLIT-LEAF when the leaf overflows. An inner node that overflows moves one of its separators up to its parent, again chosen within positions of the middle so that the shortest one moves up. A full root splits into a new root with one separator. range walks the leaves whose fence interval meets .
Example
Insert ten names in this order into a tree with at most 4 entries per node and a split interval with : Smith, Smithers, Smithson, Smythe, Smyth, Snow, Sato, Sanders, Smit, Smart. In the trace, a leaf is written as [prefix | stored keys].
- The fifth insert overflows the leaf Smith, Smithers, Smithson, Smyth, Smythe. Here , and the three candidates are with separator "Smiths", with "Smy", and with "Smythe". The shortest is "Smy". The root becomes {Smy}, and the leaves are [ | Smith Smithers Smithson] and [ | Smyth Smythe].
- Snow and Sato go into the two leaves. Sanders then overflows the left leaf Sanders, Sato, Smith, Smithers, Smithson. The candidates are "Sm" (, between Sato and Smith), "Smithe" () and "Smiths" (), so the split takes "Sm" and leaves two keys on the left.
- The middle leaf now has the fences "Sm" and "Smy", which share the prefix "Sm", so it stores [Sm | ith ithers ithson]. Smit goes into it. Smart then overflows it with the keys Smart, Smit, Smith, Smithers, Smithson. The candidates are "Smith" (, between Smit and Smith), "Smithe" () and "Smiths" (). The split takes "Smith", and the new leaf with the fences "Sm" and "Smith" stores [Sm | art it]. The shorter separator "Smi", between Smart and Smit, is at , outside the split interval, so it is not a choice.
The final tree from the code is:
| node | fences | stored prefix | stored entries |
|---|---|---|---|
| root | open | none | Sm, Smith, Smy |
| leaf 1 | open to Sm | none | Sanders, Sato |
| leaf 2 | Sm to Smith | Sm | art, it |
| leaf 3 | Smith to Smy | Sm | ith, ithers, ithson |
| leaf 4 | Smy to open | none | Smyth, Smythe, Snow |
The separators take 10 characters. With the same inserts give the separators Smi, Smithe and Smy, 12 characters, and two leaves store the prefixes "Smi" and "Sm". On a larger run, 200 random keys of the form "customer-" followed by up to 5 letters (seed 7, at most 4 entries per node) give 143 distinct keys. The inner nodes then store 183 characters of separators instead of 525 characters for the same separators written in full, and 244 instead of 565 with .
Correctness
The proofs are in proofs/correctness.md. They rest on three facts.
- Shortest separator. For , the string of L3 satisfies , and no shorter string does. Let have and . If is a prefix of , it is a prefix of too, because the first characters agree, so . Otherwise first differs from at a position with , so .
- Prefix of an interval. If and is the longest common prefix of and , then starts with . So stripping loses nothing, and the order of the stored suffixes in is the order of the full keys.
- Fence invariant. Every insert and split keeps for every key in the subtree of . Then SEARCH visits the only leaf that can hold , exactly as in a B+ tree.
Proof: Shortest separators and stored prefixes keep the prefix B-tree a correct B+ treefull
Strings are compared in lexicographic order: if is a proper prefix of , or if at the first position where they differ, . We use the notation of the page: a node has fences and (either may be open), is the longest common prefix of the two fences (empty if one is open), and an inner node with children has separators .
Lemma 1 (shortest separator). Let and let be the result of SHORTEST-SEPARATOR. Then , and every string with has .
Proof. Let be the value at which the loop of L2 stops. Then . Since , either is a proper prefix of , and then , or and , because is the first difference and . In both cases has a character at position , so has length .
because is a prefix of . For : in the first case is a proper prefix of ; in the second case and agree before and .
Now let and . If is a prefix of , then is a prefix of , so . Otherwise is not a prefix of and , so at the first position where and differ, and , so . In both cases is not in .
Lemma 2 (prefix of an interval). Let , let be their longest common prefix, and let . Then starts with . If and both lie in and , , then if and only if .
Proof. Suppose does not start with . If is a proper prefix of , then is a proper prefix of , so , which is false. Otherwise first differs from at some . If , then . If , then . Both are false. The second claim holds because removing a common prefix from two strings does not change their order.
If a fence is open, is empty and both claims hold trivially.
Invariant. (I1) The tree is a B+ tree: every leaf has the same depth, and an inner node with separators has children. (I2) The root has open fences, and child of an inner node has the fences and , where and . (I3) Every key in the subtree of , and every separator stored in , lies in , and stores each of them without the prefix , in increasing order.
By Lemma 2, (I3) is well defined: each stored item starts with , and the stored suffixes are in the same order as the full strings.
Claim 1 (SEARCH). If the invariant holds, SEARCH returns true if and only if is a key of .
Proof. We show that SEARCH visits a node with at each level. This holds for the root. At an inner node , by Lemma 2 the suffix test at L6 counts exactly the separators . So is the index with (with the conventions of I2), which by (I2) means . By (I3) for the siblings, any key equal to can only be in the subtree of , because the fence intervals of the children are disjoint. At the leaf, L8 compares the suffix of with the stored suffixes, which by Lemma 2 is the same as comparing full keys.
Claim 2 (insert keeps the invariant). Adding a key to the leaf that SEARCH reaches keeps (I3), since that leaf's interval contains the key. Consider SPLIT-LEAF on a leaf with keys in , and the split point with . By Lemma 1, $s = $ SHORTEST-SEPARATOR satisfies . So every key of the left part lies in and every key of the right part lies in . Also and , so lies strictly inside the old interval, and inserting it into the parent just after the pointer to keeps the separators of the parent sorted. The new fences of the two leaves are exactly and , as (I2) demands, and L14 stores their keys without the new prefixes, as (I3) demands.
An inner node with separators that overflows moves one separator up. The left node keeps and with the fences and ; the right node keeps and with the fences and . Every child keeps its old fences, so (I2) and (I3) hold below, and each of the two nodes stores its separators again without its new prefix. A root split makes a new root with open fences and the single separator, which keeps (I1) because both halves have the same height.
By Claims 1 and 2, after any sequence of inserts, contains answers correctly, and the leaves read from left to right give all keys in increasing order, which is what range uses. The choice of inside the split interval does not affect correctness, only the length of : by Lemma 1 the separator at each candidate point is as short as any separator at that point can be.
The tests check Lemma 1 against all strings of length at most 4 over a three-letter alphabet, Lemma 2 against all strings of length at most 4 over two letters, and the invariant, contains, the key order and range against a Python set after random inserts.
Complexity
Costs are in the page I/O model: one node is one page, and a page read is one I/O. In the external memory model, the memory holds M/B blocks; this page counts page reads only and does not use a buffer size.
- Search reads one page per level, pages, where is the number of separators that fit in an inner page. In memory it does a binary search per node with characters per comparison, in all, plus per level to strip and add back the prefix.
- Insert costs one search, plus a split at each level in the worst case. The split interval adds work per split to compare the candidate separators.
- Space is at most that of the plain B+ tree on the same keys, and usually much less in the inner levels.
- Fan-out. If separators shrink from an average of to characters and a pointer takes bytes, the fan-out grows by about . The height is and drops by one level only when grows enough; the gain in height is a measured effect that depends on the keys, not a guarantee.
Variants
- Simple prefix B-tree. Shortest separators and the split interval, but every key stored in full. Most of the gain is in the inner levels.
- Prefix truncation in leaves. Many systems store the prefix shared by the fences of a leaf once and remove it from every key of the leaf, as on this page. Graefe (2011) describes this with fence keys kept in each node.
- Front coding inside a page. Each key stores only how many characters it shares with the key before it, as in front coding. This compresses more but needs a sequential decode, so binary search in the page becomes harder.
- Normalized keys. Multi-column keys are first mapped to one byte string whose order is the order of the columns, so that the string methods of this page apply to any key type.
- Tries. A trie or an adaptive radix tree stores each shared prefix once for all keys, not once per node, and has no separators at all, at the cost of a less regular page layout.
When to use it
Use it for B+ trees on long string keys that share prefixes, such as URLs, file paths, names and composite keys. Most disk-based database systems use some of these ideas in their B-tree code. For short fixed-size integer keys the gain is small, because a separator cannot be shorter than one byte of difference.
Pitfalls
- Wrong separator convention. The shortest separator must respect the rule used by the search. With "left < s ≤ right", the separator is a prefix of the first key on the right. A search that treats an equal key as belonging to the left goes wrong.
- Choosing a separator from a deleted key. A separator does not need to be a key of the tree. Code that assumes it is, for example to find "the key equal to the separator", breaks after deletes.
- Prefixes after a split. A split changes the fences of the two new nodes, so their prefixes can change. Every stored key must be stored again with the new prefix, as L14 does.
- Too wide a split interval. A large gives very uneven splits and lowers the fill of the pages. Keep small against the number of entries in a node.
- Fan-out in entries. If the page capacity is a count of entries, short separators save nothing. The gain comes only when a page holds as many entries as fit in its bytes.
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/prefix-b-tree/. The authors are listed in prov/AJZDXP.jsonl.
"""Prefix B-tree (Bayer and Unterauer 1977) on string keys.
A B+ tree: the keys are in the leaves, and the inner nodes hold separators.
A separator s between a left node and a right node satisfies
left keys < s <= right keys. Two ideas of the paper are used:
* simple prefix B-tree: a leaf split puts the shortest separator between the
two halves into the parent, and the split point is chosen inside a split
interval of 2 d + 1 positions so that this separator is short;
* prefix B-tree: every key in a node lies between the two fences of the node
(the separators that bound it in its parent, or the fences of the parent),
so all keys of the node start with the common prefix of the fences. The
node stores its keys and separators without that prefix.
Capacity is counted in entries to keep the code short; real systems count
bytes, which is where short separators pay off.
"""
from bisect import bisect_left, bisect_right, insort
from typing import Iterator, List, Optional, Tuple
def shortest_separator(a: str, b: str) -> str:
"""SHORTEST-SEPARATOR: the shortest s with a < s <= b, for a < b."""
if not a < b:
raise ValueError("need a < b")
i = 0 # @line L1
while i < len(a) and a[i] == b[i]: # @line L2
i += 1 # @line L2
return b[: i + 1] # @line L3
def common_prefix(low: Optional[str], high: Optional[str]) -> str:
"""The prefix that every key in [low, high) has. An open end gives ''."""
if low is None or high is None:
return ""
i = 0
while i < len(low) and i < len(high) and low[i] == high[i]:
i += 1
return low[:i]
class Node:
"""A node with fences [low, high). keys holds suffixes after the prefix.
In a leaf, keys are the stored keys. In an inner node, keys are the
separators, and len(children) == len(keys) + 1.
"""
def __init__(self, leaf: bool, low: Optional[str], high: Optional[str]):
self.leaf = leaf
self.low = low
self.high = high
self.prefix = common_prefix(low, high)
self.keys: List[str] = []
self.children: List["Node"] = []
def full_keys(self) -> List[str]:
return [self.prefix + s for s in self.keys]
def set_fences(self, low: Optional[str], high: Optional[str]) -> None:
"""Change the fences and store the keys again without the new prefix."""
full = self.full_keys()
self.low, self.high = low, high
self.prefix = common_prefix(low, high)
self.keys = [k[len(self.prefix):] for k in full]
class PrefixBTree:
def __init__(self, capacity: int = 4, d: int = 1):
"""capacity: the largest number of keys or separators in a node.
d: the half width of the split interval (d = 0 splits in the middle).
"""
if capacity < 3:
raise ValueError("capacity must be at least 3")
self.capacity = capacity
self.d = d
self.root = Node(True, None, None)
# ----- search -----
def _child_index(self, v: Node, k: str) -> int:
# k lies in [v.low, v.high), so it starts with v.prefix.
return bisect_right(v.keys, k[len(v.prefix):]) # @line L6
def _leaf_for(self, k: str) -> Tuple[Node, List[Tuple[Node, int]]]:
v = self.root # @line L4
path = []
while not v.leaf: # @line L5
j = self._child_index(v, k) # @line L6
path.append((v, j))
v = v.children[j] # @line L7
return v, path
def contains(self, k: str) -> bool:
"""SEARCH."""
v, _ = self._leaf_for(k)
s = k[len(v.prefix):]
i = bisect_left(v.keys, s)
return i < len(v.keys) and v.keys[i] == s # @line L8
# ----- insert -----
def insert(self, k: str) -> bool:
"""Insert k; return False if it was already there."""
if not isinstance(k, str):
raise TypeError("keys are strings")
v, path = self._leaf_for(k)
s = k[len(v.prefix):]
i = bisect_left(v.keys, s)
if i < len(v.keys) and v.keys[i] == s:
return False
v.keys.insert(i, s)
while len(v.keys) > self.capacity:
parent = path.pop()[0] if path else None
if v.leaf:
sep, right = self._split_leaf(v)
else:
sep, right = self._split_inner(v)
if parent is None:
root = Node(False, None, None)
root.keys = [sep]
root.children = [v, right]
self.root = root
break
j = parent.children.index(v)
parent.keys.insert(j, sep[len(parent.prefix):]) # @line L13
parent.children.insert(j + 1, right) # @line L13
v = parent
return True
def _choose(self, n: int, sep_of) -> int:
"""The split index j in the split interval with the shortest separator."""
c = (n + 1) // 2 # @line L9
lo, hi = max(1, c - self.d), min(n - 1, c + self.d)
best = None
for j in range(lo, hi + 1): # @line L10
key = (len(sep_of(j)), abs(j - c), j)
if best is None or key < best:
best = key
return best[2]
def _split_leaf(self, v: Node) -> Tuple[str, Node]:
full = v.full_keys()
n = len(full)
j = self._choose(n, lambda t: shortest_separator(full[t - 1], full[t])) # @line L10
sep = shortest_separator(full[j - 1], full[j]) # @line L11
right = Node(True, sep, v.high) # @line L12
right.keys = [x[len(right.prefix):] for x in full[j:]] # @line L14
v.keys = [x[len(v.prefix):] for x in full[:j]] # @line L12
v.set_fences(v.low, sep) # @line L14
return sep, right
def _split_inner(self, v: Node) -> Tuple[str, Node]:
full = v.full_keys()
n = len(full)
# Separator t moves up; the left node keeps full[:t] and the right full[t+1:].
t = self._choose(n - 1, lambda u: full[u]) if n > 2 else 1
sep = full[t]
right = Node(False, sep, v.high)
right.keys = [x[len(right.prefix):] for x in full[t + 1:]]
right.children = v.children[t + 1:]
v.keys = [x[len(v.prefix):] for x in full[:t]]
v.children = v.children[: t + 1]
v.set_fences(v.low, sep)
self._refence(v)
self._refence(right)
return sep, right
def _refence(self, v: Node) -> None:
"""Give each child of v the fences that v now implies."""
bounds = [v.low] + v.full_keys() + [v.high]
for i, c in enumerate(v.children):
c.set_fences(bounds[i], bounds[i + 1])
# ----- scans and checks -----
def range(self, lo: str, hi: str) -> List[str]:
"""All keys k with lo <= k <= hi, in order."""
out: List[str] = []
self._collect(self.root, lo, hi, out)
return out
def _collect(self, v: Node, lo: str, hi: str, out: List[str]) -> None:
if v.high is not None and v.high <= lo:
return
if v.low is not None and v.low > hi:
return
if v.leaf:
out.extend(k for k in v.full_keys() if lo <= k <= hi)
return
for c in v.children:
self._collect(c, lo, hi, out)
def keys(self) -> List[str]:
out: List[str] = []
self._all(self.root, out)
return out
def _all(self, v: Node, out: List[str]) -> None:
if v.leaf:
out.extend(v.full_keys())
else:
for c in v.children:
self._all(c, out)
def height(self) -> int:
h, v = 1, self.root
while not v.leaf:
h, v = h + 1, v.children[0]
return h
def stored_chars(self) -> Tuple[int, int]:
"""(characters of separators as stored, characters of the full separators)."""
stored = full = 0
stack = [self.root]
while stack:
v = stack.pop()
if not v.leaf:
stored += sum(len(s) for s in v.keys)
full += sum(len(s) for s in v.full_keys())
stack.extend(v.children)
return stored, full
def check(self) -> None:
"""Raise AssertionError if an invariant of the page fails."""
depths = set()
self._check(self.root, None, None, 1, depths)
assert len(depths) == 1, "leaves at different depths"
def _check(self, v: Node, low, high, depth, depths) -> None:
assert v.low == low and v.high == high, "wrong fences"
assert v.prefix == common_prefix(low, high)
full = v.full_keys()
assert full == sorted(full) and len(set(full)) == len(full)
assert len(full) <= self.capacity
for k in full:
assert low is None or low <= k
assert high is None or k < high
if v.leaf:
depths.add(depth)
return
assert len(v.children) == len(v.keys) + 1
bounds = [low] + full + [high]
for i, c in enumerate(v.children):
self._check(c, bounds[i], bounds[i + 1], depth + 1, depths)
test_prefix_b_tree.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/prefix-b-tree/. The authors are listed in prov/AJZDXP.jsonl.
import itertools
import random
import unittest
from prefix_b_tree import PrefixBTree, common_prefix, shortest_separator
def all_strings(alphabet, max_len):
out = [""]
for n in range(1, max_len + 1):
out.extend("".join(t) for t in itertools.product(alphabet, repeat=n))
return out
def random_key(rng, alphabet="abc", max_len=6):
return "".join(rng.choice(alphabet) for _ in range(rng.randint(1, max_len)))
class TestShortestSeparator(unittest.TestCase):
def test_against_brute_force(self):
strings = sorted(set(all_strings("abc", 3)))
candidates = all_strings("abc", 4)
for a in strings:
for b in strings:
if not a < b:
continue
s = shortest_separator(a, b)
self.assertTrue(a < s <= b)
best = min(len(t) for t in candidates if a < t <= b)
self.assertEqual(len(s), best)
def test_examples(self):
self.assertEqual(shortest_separator("Smith", "Smyth"), "Smy")
self.assertEqual(shortest_separator("cat", "catalog"), "cata")
self.assertEqual(shortest_separator("apple", "banana"), "b")
with self.assertRaises(ValueError):
shortest_separator("b", "a")
def test_common_prefix_is_shared_by_the_interval(self):
strings = all_strings("ab", 4)
for low in strings:
for high in strings:
if not low < high:
continue
p = common_prefix(low, high)
for k in strings:
if low <= k < high:
self.assertTrue(k.startswith(p))
class TestPrefixBTree(unittest.TestCase):
def test_against_a_sorted_set(self):
for seed in range(12):
rng = random.Random(seed)
t = PrefixBTree(capacity=rng.choice([3, 4, 5, 8]), d=rng.choice([0, 1, 2]))
ref = set()
for _ in range(rng.randint(1, 200)):
k = random_key(rng)
self.assertEqual(t.insert(k), k not in ref)
ref.add(k)
t.check()
self.assertEqual(t.keys(), sorted(ref))
for _ in range(60):
k = random_key(rng)
self.assertEqual(t.contains(k), k in ref)
for _ in range(30):
lo, hi = sorted([random_key(rng), random_key(rng)])
self.assertEqual(t.range(lo, hi), sorted(x for x in ref if lo <= x <= hi))
def test_sorted_and_reverse_inserts(self):
keys = sorted(set(all_strings("abcd", 3)) - {""})
for order in (keys, keys[::-1]):
t = PrefixBTree(capacity=4, d=1)
for k in order:
t.insert(k)
t.check()
self.assertEqual(t.keys(), keys)
self.assertTrue(all(t.contains(k) for k in keys))
self.assertFalse(t.contains("e"))
def test_prefix_truncation_saves_characters(self):
rng = random.Random(7)
t = PrefixBTree(capacity=4, d=1)
for _ in range(200):
t.insert("customer-" + random_key(rng, "abcdef", 5))
t.check()
stored, full = t.stored_chars()
self.assertLess(stored, full)
def test_split_interval_shortens_separators(self):
keys = ["aaaa", "aaab", "aaac", "aaad", "b"]
mid = PrefixBTree(capacity=4, d=0)
wide = PrefixBTree(capacity=4, d=1)
for k in keys:
mid.insert(k)
wide.insert(k)
self.assertEqual(mid.root.full_keys(), ["aaad"])
self.assertEqual(wide.root.full_keys(), ["b"])
mid.check()
wide.check()
def test_hand_cases(self):
t = PrefixBTree(capacity=3)
self.assertFalse(t.contains("a"))
self.assertEqual(t.range("a", "z"), [])
self.assertTrue(t.insert("a"))
self.assertFalse(t.insert("a"))
with self.assertRaises(TypeError):
t.insert(3)
with self.assertRaises(ValueError):
PrefixBTree(capacity=2)
if __name__ == "__main__":
unittest.main()
History
Rudolf Bayer and Karl Unterauer at the Technical University of Munich published "Prefix B-trees" in ACM Transactions on Database Systems in March 1977, after an IBM research report of 1976. They described the simple prefix B-tree, with short separators in the index part, and the prefix B-tree, in which the prefixes are not stored but rebuilt as the tree is searched. Graefe's survey of 2011 describes how these ideas, together with fence keys and normalized keys, are used in current B-tree code.
References
- Rudolf Bayer and Karl Unterauer, Prefix B-trees, ACM Transactions on Database Systems 2(1) (1977), pp. 11 to 26, the simple prefix B-tree (shortest separators in the index part, the split interval) and the prefix B-tree (prefixes that are not stored but rebuilt during the search)
- Goetz Graefe, Modern B-tree techniques, Foundations and Trends in Databases 3(4) (2011), pp. 203 to 402, the sections on compression of keys in B-tree nodes (prefix truncation, shortened separator keys, fence keys); section level only
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 | W2 basic |
|
Tag AJZDXP Edit this page History Report an error Markdown