Sub topic 4
Searching a B-tree
This chapter assumes you know binary search on a sorted array and what a B-tree node looks like: a sorted list of keys and, in internal nodes, one more child pointer than keys. Searching a B-tree combines two steps at each node: a binary search among the node's keys, then a jump to one child.
The rule for choosing a child
Take an internal node with keys [5, 12] and three children. Each child covers a key range:
| Child | Keys it can contain |
|---|---|
| `children[0]` | less than 5 |
| `children[1]` | between 5 and 12 |
| `children[2]` | greater than 12 |
If i is the position where the target key would be inserted in the node's sorted keys, children[i] is the only child that can contain the target. The search never has to look at the other children.
The algorithm
- Binary search the current node's keys for the target.
- If the key is there, return it.
- If the node is a leaf, the key is absent. Stop.
- Otherwise move to the child at the insertion position and repeat.
from bisect import bisect_left
class Node:
def __init__(self, keys, children=None):
self.keys = keys # sorted list of keys
self.children = children # None for a leaf, else len(keys) + 1 child nodes
def search(node, key):
i = bisect_left(node.keys, key)
if i < len(node.keys) and node.keys[i] == key:
return True
if node.children is None:
return False
return search(node.children[i], key)
leaf_a = Node([1, 3])
leaf_b = Node([7, 9])
leaf_c = Node([15, 20])
root = Node([5, 12], [leaf_a, leaf_b, leaf_c])
print(search(root, 9)) # True
print(search(root, 10)) # Falsebisect_left returns the index of the first key that is greater than or equal to the target. That index is both the match position (if the key exists) and the child index to follow (if it does not).
Tracing two lookups
For search(root, 9), bisect_left([5, 12], 9) returns 1. keys[1] is 12, not 9, so the search follows children[1], the leaf [7, 9]. There bisect_left returns 1 and keys[1] is 9, so the result is True.
For search(root, 10), the path is the same. In the leaf, bisect_left([7, 9], 10) returns 2, which is past the end of the list. The key is not present, and a leaf has no children, so the result is False.
Cost: one page per level
In a database, each node is one page on disk. A lookup reads one page per level, so the number of page reads equals the tree height. With the fanout of about 512 computed earlier, a tree of height 3 covers over 134 million keys. A lookup therefore needs at most three page reads. In practice the root and often the second level stay in memory, so the real disk reads are fewer.
The binary search inside a page costs only CPU time on data already in memory, which is cheap next to a disk read.
Common errors
- Skipping the equality check in internal nodes. In a B-tree, internal nodes also hold keys. If you only compare at leaves, you miss matches that sit higher up. B+trees, covered later, move all entries to the leaves.
- Off-by-one in the child index. A node with
nkeys hasn + 1children. Usingi - 1ori + 1sends the search into the wrong range. - Scanning keys linearly. This works for tiny nodes but wastes CPU on pages with hundreds of keys. Use binary search.
- Treating "not found" as an error path. Reaching a leaf without a match is the normal answer for a missing key. It costs as many page reads as a successful lookup.
Exercise
Using the tree built in the code above, which nodes does search(root, 20) visit, and what does it return?
Show answer
It visits the root [5, 12] and then the leaf [15, 20]. In the root, bisect_left([5, 12], 20) returns 2, which is past the end, so the search follows children[2]. In that leaf, bisect_left returns 1 and keys[1] equals 20, so it returns True after reading two nodes.