Sub topic 5
Inserting keys and splitting nodes
This chapter assumes you know how a B-tree search works (binary search inside a node, then follow one child pointer) and what a page is. Here you will see what happens when a key lands in a node that has no room left.
Where a new key goes
A B-tree keeps every leaf at the same depth. An insert therefore never hangs a new leaf off the bottom. It follows these steps:
- Search for the key, as you would for a lookup. The search ends at a leaf.
- Insert the key into that leaf at its sorted position.
- If the leaf now holds more keys than its maximum, split it.
Most inserts stop at step 2. They change one page and nothing else.
The split
A node that exceeds its maximum is divided into two nodes:
- The left node keeps the lower half of the keys.
- The right node gets the upper half.
- The middle key (the median) moves up into the parent. It becomes the separator between the two new nodes.
The parent gains one key and one child pointer. If the parent is now over its maximum, it splits the same way. The split can repeat up the path toward the root.
Growing the tree
If the root splits, there is no parent to receive the median. The tree creates a new root holding only that median, with the two halves as its children. This is the only way a B-tree gets taller. Height increases at the top, so every leaf stays at the same depth and lookup cost stays uniform.
An implementation
This version uses a maximum of 3 keys per node so that splits happen early. The recursive insert returns None if nothing split. Otherwise it returns the median and the new right node for the caller to add to its own keys.
from bisect import bisect_left
MAX_KEYS = 3
class Node:
def __init__(self, keys=None, children=None):
self.keys = keys or []
self.children = children # None for a leaf
def insert(node, key):
i = bisect_left(node.keys, key)
if i < len(node.keys) and node.keys[i] == key:
return None # duplicate, ignore
if node.children is None:
node.keys.insert(i, key)
else:
result = insert(node.children[i], key)
if result is not None:
median, right = result
node.keys.insert(i, median)
node.children.insert(i + 1, right)
if len(node.keys) <= MAX_KEYS:
return None
mid = len(node.keys) // 2
median = node.keys[mid]
right = Node(node.keys[mid + 1:],
node.children[mid + 1:] if node.children else None)
node.keys = node.keys[:mid]
if node.children:
node.children = node.children[:mid + 1]
return median, right
def insert_key(root, key):
result = insert(root, key)
if result is None:
return root
median, right = result
return Node([median], [root, right]) # tree grows taller
def show(node, depth=0):
print(" " * depth + str(node.keys))
for child in node.children or []:
show(child, depth + 1)
root = Node()
for k in range(1, 8):
root = insert_key(root, k)
show(root)
# [3, 6]
# [1, 2]
# [4, 5]
# [7]Inserting 1 to 7 in order splits the leaf twice. After the first split (on 4) the root is [3]. After the second (on 7) the median 6 joins the root.
Costs and common errors
- Write cost. A split writes at least three pages: the two halves and the parent. A database must also log these changes so a crash cannot leave a half-finished split. That is covered in a later chapter.
- Sequential keys. Inserting ever-increasing keys, such as auto-increment IDs, always fills the rightmost leaf. Splits happen only at that edge, and the left pages stay full.
- Random keys. Random keys, such as UUIDs, hit leaves all over the tree. Splits are more frequent and leave many pages about half full.
- Wrong median. A frequent bug is to keep the median in the left node as well as sending it up. In a B-tree the median moves up. (A B+tree differs here, as the next chapters show.)
Exercise
With MAX_KEYS = 3, a leaf holds [10, 20, 30] and its parent has room. You insert 25. Which keys end up in the left leaf, the right leaf, and the parent's new separator?
Show answer
The leaf becomes [10, 20, 25, 30] and splits at index 2. The median 25 moves up to the parent as the separator. The left leaf is [10, 20] and the right leaf is [30].