❖ B-Trees |
B-trees are multi-way search trees with the properties:
❖ B-Trees (cont) |
Example B-tree (depth=3, n=3)
(Note: in DBs, nodes are pages ⇒ large branching factor, e.g. n=500)
❖ B-Tree Depth |
Depth depends on effective branching factor (i.e. how full nodes are).
Simulation studies show typical B-tree nodes are 69% full.
Gives load Li = 0.69 × ci and depth of tree ~ ceil( logLi r ).
Example: ci=128, Li=88
Level | #nodes | #keys |
root | 1 | 88 |
1 | 89 | 7832 |
2 | 7921 | 697048 |
3 | 704969 | 62037272 |
❖ Selection with B-Trees |
For one queries:
Node find(k,tree) {
return search(k, root_of(tree))
}
Node search(k, node) {
// get the page of the node
if (is_leaf(node)) return node
keys = array of nk key values in node
pages = array of nk+1 ptrs to child nodes
if (k <= keys[0])
return search(k, pages[0])
else if (keys[i] < k <= keys[i+1])
return search(k, pages[i+1])
else if (k > keys[nk-1])
return search(k, pages[nk])
}
❖ Selection with B-Trees (cont) |
Simplified description of search ...
N = B-tree root node while (N is not a leaf node) N = scanToFindChild(N,K) tid = scanToFindEntry(N,K) access tuple T using tid
Costone = (D + 1)r
❖ Selection with B-Trees (cont) |
For range queries (assume sorted on index attribute):
search index to find leaf node for Lo for each leaf node entry until Hi found add pageOf(tid) to Pages to be scanned scan Pages looking for matching tuples
Costrange = (D + bi + bq)r
❖ Insertion into B-Trees |
Overview of the method:
❖ Example: B-tree Insertion |
Starting from this tree:
insert the following keys in the given order 12 15 30 10
❖ B-Tree Insertion Cost |
Insertion cost = CosttreeSearch + CosttreeInsert + CostdataInsert
Best case: write one page (most of time)
Common case: 3 node writes (rearrange 2 leaves + parent)
❖ B-Tree Insertion Cost (cont) |
Worst case: propagate to root Costinsert = Dr + D.3w + 1r + 1w
❖ B-trees in PostgreSQL |
PostgreSQL implements ≅ Lehman/Yao-style B-trees
backend/access/nbtree
README
nbtree.c
nbtsearch.c
nbtinsert.c
❖ B-trees in PostgreSQL (cont) |
Changes for PostgreSQL v12
\di+ IndexName
select * from bt_page_items(IndexName,BlockNo)
❖ B-trees in PostgreSQL (cont) |
Interface functions for B-trees
// build Btree index on relation Datum btbuild(rel,index,...) // insert index entry into Btree Datum btinsert(rel,key,tupleid,index,...) // start scan on Btree index Datum btbeginscan(rel,key,scandesc,...) // get next tuple in a scan Datum btgettuple(scandesc,scandir,...) // close down a scan Datum btendscan(scandesc)
Produced: 15 Mar 2023