计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 3 · 本科三年级

21Database Storage and Indexes

A table of the town’s loans is, to the programmer who queries it, a set of rows. To the disk it is a file of pages, and the price of every query is the number of pages it reads and writes. This chapter builds that file from the bottom: the slotted page that holds records, the buffer pool that keeps hot pages in memory, and three kinds of index on top of them, the B+ tree, the hash index and the log-structured merge tree. Every structure counts its page reads, so that each claim about cost is a number printed by a program. The chapter ends with SQLite, whose file is read byte by byte and whose query planner is watched choosing an index on the town’s loans.

You already know

A balanced search tree keeps nn keys in sorted order with height O(log⁡n)O(\log n); a hash table finds a key in expected constant time (Year 1 volume). A Bloom filter answers “maybe present” or “certainly absent” with a few bits per key and a tunable false-positive rate (Year 2 volume). A relational table is a set of rows queried with SQL, and an index on a column makes lookups on that column fast (Year 1 and Year 2 volumes). The clock algorithm approximates least-recently-used replacement with one reference bit per frame (Definition 11.5). Write amplification is the ratio of bytes physically written to bytes the program asked to write (Definition 12.3).

21.1 Pages, records and the buffer pool

Definition 21.1 (Database page, slotted page, record identifier)

A database page is the unit in which a database file is read and written: a fixed number of bytes, here 4,096, at a known position in the file. A slotted page stores variable-length records in a page: a header, then a slot array growing from the front, one entry (offset, length) per record, then free space, then the records themselves, growing from the back of the page. A record identifier is the pair (page number, slot number); it names a record for as long as it lives, wherever the record moves inside its page.

The slot array is the indirection that makes record identifiers stable: an index can point to (17, 3) and the page is free to slide its records around to merge free space, since only the slot’s offset changes. pagefile.py is the file of the chapter, kept in memory but counting every page read and write; slotted.py lays out one page with a 4-byte header (the number of slots, the start of the records) and 4-byte slots.

PAGE = 4096


class PageFile:
    def __init__(self):
        self.pages, self.reads, self.writes = [], 0, 0

    def allocate(self):
        self.pages.append(bytes(PAGE))
        return len(self.pages) - 1  # the new page's number

    def read(self, pid):
        self.reads += 1
        return bytearray(self.pages[pid])

    def write(self, pid, data):
        assert len(data) == PAGE
        self.writes += 1
        self.pages[pid] = bytes(data)
Listing 21.1. A file of pages that counts its reads and writes. code/bachelor-3/21-database-storage/listings/pagefile.py
    def insert(self, record):
        count, start = self.header()
        empty = [i for i in range(count) if self.slot(i)[1] == 0]
        need = len(record) + (0 if empty else SLOT.size)
        if need > self.free_space():
            return None  # the page is full
        start -= len(record)
        self.data[start : start + len(record)] = record
        i = empty[0] if empty else count
        SLOT.pack_into(self.data, HEADER.size + i * SLOT.size, start, len(record))
        HEADER.pack_into(self.data, 0, max(count, i + 1), start)
        return i

    def get(self, i):
        offset, length = self.slot(i)
        return bytes(self.data[offset : offset + length]) if length else None

    def delete(self, i):
        SLOT.pack_into(self.data, HEADER.size + i * SLOT.size, 0, 0)
Listing 21.2. A slotted page: insert reuses an empty slot or grows the array; delete empties the slot. code/bachelor-3/21-database-storage/listings/slotted.py
$ python slotted_demo.py
five records: 5 slots, records from byte 4021, free 3997
  slots (offset+length): 0:4079+17 1:4063+16 2:4051+12 3:4036+15 4:4021+15
slots 1 and 3 deleted: 5 slots, records from byte 4021, free 3997
  slots (offset+length): 0:4079+17 1:0+0 2:4051+12 3:0+0 4:4021+15
one inserted in slot 1: 5 slots, records from byte 4004, free 3980
  slots (offset+length): 0:4079+17 1:4004+17 2:4051+12 3:0+0 4:4021+15
compacted: 5 slots, records from byte 4035, free 4011
  slots (offset+length): 0:4079+17 1:4062+17 2:4050+12 3:0+0 4:4035+15
record 4 is still b'5,Vera,Lakewick'
all 120 people offered to an empty page: 120 fit, 798 bytes free
Output 21.1. Five of the town’s people in one page. The insertion reuses slot 1; compaction moves records but keeps every slot number, so record 4 is found again.
The first page of , not to scale: a 4-byte header, five 4-byte slots ending at byte 24, 3,997 free bytes, and the records from byte 4,021 to the end, record 0 last.
The first page of Output 21.1, not to scale: a 4-byte header, five 4-byte slots ending at byte 24, 3,997 free bytes, and the records from byte 4,021 to the end, record 0 last.

A database cannot keep its file in memory, and cannot afford to read a page from disk at each access either. It keeps a fixed number of page-sized frames in memory and caches pages in them.

Definition 21.2 (Buffer pool, pin count, dirty page)

A buffer pool is a fixed set of frames in memory, each holding one page of the database file, with a table from page numbers to frames. A frame’s pin count is the number of users currently holding its page; a pinned frame is never chosen for replacement. A dirty page is a page changed in its frame and not yet written back; it is written to the file before its frame is reused.

The buffer pool is the operating system’s page cache moved into the database, which then decides itself when a page goes to disk: a write-ahead log, told in Chapter 23, needs exactly that control. Victims are chosen by the clock algorithm, skipping pinned frames.

    def fetch(self, pid):
        if pid in self.where:
            self.hits += 1
            f = self.where[pid]
        else:
            self.misses += 1
            f = self.victim()
            if self.page[f] is not None:
                if self.dirty[f]:
                    self.file.write(self.page[f], self.data[f])
                del self.where[self.page[f]]
            self.page[f], self.data[f], self.dirty[f] = pid, self.file.read(pid), False
            self.where[pid] = f
        self.pins[f] += 1
        self.ref[f] = True
        return self.data[f]

    def unpin(self, pid, dirty=False):
        f = self.where[pid]
        self.pins[f] -= 1
        self.dirty[f] |= dirty

    def victim(self):
        """Clock: sweep the frames, clearing reference bits, until an unpinned frame
        whose bit is already clear; a frame never used is taken at once."""
        for _ in range(2 * self.n + 1):
            f, self.hand = self.hand, (self.hand + 1) % self.n
            if self.page[f] is None:
                return f
            if self.pins[f] == 0:
                if not self.ref[f]:
                    return f
                self.ref[f] = False
        raise RuntimeError("every frame is pinned")
Listing 21.3. Fetch, unpin and the clock: a miss writes back a dirty victim before reading the page. code/bachelor-3/21-database-storage/listings/bufferpool.py
$ python buffer_demo.py
frames   hit rate   page reads   page writes
    10      3.6%       48,189         4,986
    50     17.2%       41,404         4,912
   100     33.5%       33,259         4,790
   200     60.8%       19,623         4,259
   400     86.4%        6,819         1,385
  1000     98.0%        1,000           690
Output 21.2. Hit rate against pool size on 50,000 accesses to 1,000 pages, 80 % of them to a hot fifth. One access in ten changes its page.

With 200 frames the pool is as large as the hot set, yet hits only 61 % of the time: the cold accesses keep evicting hot pages. Twice the hot set gives 86 %, and a pool as large as the file misses only on the first touch of each page, 1,000 reads in all. Page writes fall with the pool too, since a page changed ten times in its frame is written once.

SQLite, the database inside Python’s sqlite3 module, documents its file format exactly, and the file can be read with nothing more than struct. The first 100 bytes of page 1 are the file header, every integer big-endian: the string SQLite format 3 and a zero byte, the page size at offset 16, the size of the database in pages at offset 28, the text encoding at offset 56. Its pages are slotted too: after a page header of 8 or 12 bytes comes a cell pointer array, then unallocated space, then the cells, the records, at the end of the page. The default page size has been 4,096 bytes since version 3.12.0 of 2016; it was almost always 1,024 before.

header = raw[:100]
page_size = struct.unpack_from(">H", header, 16)[0]
fields = {
    "magic string": header[:16],
    "page size (bytes)": 65536 if page_size == 1 else page_size,
    "write / read format versions": (header[18], header[19]),
    "reserved bytes per page": header[20],
    "file change counter": struct.unpack_from(">I", header, 24)[0],
    "database size (pages)": struct.unpack_from(">I", header, 28)[0],
    "schema format number": struct.unpack_from(">I", header, 44)[0],
    "text encoding (1 = UTF-8)": struct.unpack_from(">I", header, 56)[0],
}
Listing 21.4. The header fields decoded at the offsets of the format’s documentation. code/bachelor-3/21-database-storage/listings/sqlite_header.py
$ python sqlite_header.py
magic string                   b'SQLite format 3\x00'
page size (bytes)              4096
write / read format versions   (1, 1)
reserved bytes per page        0
file change counter            2
database size (pages)          9
schema format number           4
text encoding (1 = UTF-8)      1
file size 36,864 bytes = 9 pages of 4096
SQLite library version 3.37.2
Output 21.3. A table of 2,000 short rows takes nine pages of 4,096 bytes; the header’s page count agrees with the file’s size.

21.2 B+ trees

A search tree on disk should be short and wide: every node visited is a page read, so a node should fill a page and have as many children as a page can name. Rudolf Bayer and Edward McCreight published such trees in 1972 for the indexes of large files; Douglas Comer’s survey of 1979 calls them ubiquitous and describes the variant that keeps every record in the leaves, the B+ tree.

Definition 21.3 (B+ tree, order, fill factor, node split, bulk loading)

A B+ tree of order m≥3m \ge 3 is a search tree whose nodes are pages. An internal node holds kk sorted keys and k+1k + 1 children, at most mm children; the subtree left of key KK holds keys less than KK, the subtree right of it keys at least KK. The leaves hold the (key, value) pairs, at most m−1m - 1 of them, all at the same depth and chained left to right. Every node except the root has at least ⌈m/2⌉\lceil m/2 \rceil children (internal) or ⌈(m−1)/2⌉\lceil (m - 1)/2 \rceil pairs (leaf). The fill factor is the fraction of a node’s capacity in use. A node split divides an overfull node into two and adds a separating key to the parent. Bulk loading builds a tree from sorted pairs bottom up, filling leaves in order and then each level above, without a split.

Search follows one path from the root: at each internal node, the child after the last key at most the searched key.

Insertion puts the pair in its leaf. A leaf that overflows splits in two and copies its right half’s first key up into the parent, since that key must stay in a leaf with its value; an internal node that overflows splits around its middle key and moves that key up, keeping it in neither half. A split may climb to the root, and a root that splits gives the tree a new root, one level higher: a B+ tree grows at the top, which is why all its leaves stay at the same depth.

    def insert(self, key, value):
        split = self._insert(self.root, key, value)
        if split:  # the root split: a new root one level up
            sep, right = split
            root = self.new(leaf=False)
            self.nodes[root].keys, self.nodes[root].kids = [sep], [self.root, right]
            self.root = root

    def _insert(self, pid, key, value):
        n = self.node(pid)
        if n.leaf:
            i = bisect_left(n.keys, key)
            if i < len(n.keys) and n.keys[i] == key:
                n.kids[i] = value  # replace
                return None
            n.keys.insert(i, key)
            n.kids.insert(i, value)
            self.writes += 1
            return self.split_leaf(pid) if len(n.keys) > self.m - 1 else None
        i = bisect_right(n.keys, key)
        split = self._insert(n.kids[i], key, value)
        if split:
            sep, right = split
            n.keys.insert(i, sep)
            n.kids.insert(i + 1, right)
            self.writes += 1
            return self.split_internal(pid) if len(n.kids) > self.m else None
        return None
Listing 21.6. Insertion: recurse to the leaf, and pass a split back up. code/bachelor-3/21-database-storage/listings/bptree.py
    def split_leaf(self, pid):
        """The upper half moves to a new leaf; its first key is COPIED up."""
        n, r = self.nodes[pid], self.new(leaf=True)
        right, half = self.nodes[r], len(self.nodes[pid].keys) // 2
        right.keys, right.kids = n.keys[half:], n.kids[half:]
        n.keys, n.kids = n.keys[:half], n.kids[:half]
        right.next, n.next = n.next, r
        return right.keys[0], r

    def split_internal(self, pid):
        """The middle key MOVES up: it stays in neither half."""
        n, r = self.nodes[pid], self.new(leaf=False)
        right, half = self.nodes[r], len(self.nodes[pid].keys) // 2
        sep = n.keys[half]
        right.keys, right.kids = n.keys[half + 1 :], n.kids[half + 1 :]
        n.keys, n.kids = n.keys[:half], n.kids[: half + 1]
        return sep, r
Listing 21.7. The two splits: a leaf key is copied up, an internal key is moved up. code/bachelor-3/21-database-storage/listings/bptree.py
The order-4 tree of  after inserting 5, 15, 25, 35, 45, 20, 30, 10, 40, 50. Every key of an internal node is also in a leaf, the first of the leaf to its right; the leaf chain carries range scans.
The order-4 tree of Output 21.4 after inserting 5, 15, 25, 35, 45, 20, 30, 10, 40, 50. Every key of an internal node is also in a leaf, the first of the leaf to its right; the leaf chain carries range scans.

Theorem 21.4 (Height of a B+ tree)

A B+ tree of order mm with n≥1n \ge 1 keys and h≥2h \ge 2 levels satisfies n≥2⌈m/2⌉h−2⌈(m−1)/2⌉n \ge 2 \lceil m/2 \rceil^{h-2} \lceil (m-1)/2 \rceil, so

h≤2+log⁡⌈m/2⌉n2⌈(m−1)/2⌉,which for even m is h≤1+log⁡m/2n2.h \le 2 + \log_{\lceil m/2 \rceil} \frac{n}{2 \lceil (m-1)/2 \rceil}, \qquad\text{which for even } m \text{ is } h \le 1 + \log_{m/2} \frac{n}{2}.

A search reads hh pages, O(log⁡mn)O(\log_m n), and an insertion reads hh and writes at most 2h+12h + 1.

Proof. The root, being internal when h≥2h \ge 2, has at least 2 children. Each internal node on the h−2h - 2 levels below it has at least ⌈m/2⌉\lceil m/2 \rceil children, so there are at least 2⌈m/2⌉h−22 \lceil m/2 \rceil^{h-2} leaves, each with at least ⌈(m−1)/2⌉\lceil (m-1)/2 \rceil keys. Taking logarithms gives the bound on hh. For even mm, ⌈(m−1)/2⌉=m/2\lceil (m-1)/2 \rceil = m/2 and log⁡m/2(n/m)=log⁡m/2(n/2)−1\log_{m/2}(n/m) = \log_{m/2}(n/2) - 1. An insertion reads the hh nodes of its path; each split writes the node, its new sibling and, at the top, a new root. ∎

$ python bptree_demo.py
random inserts: order 255, height 3, 534 pages, 529 leaves, 189 keys per leaf
  1,000 lookups: 3,000 page reads, 3 per lookup
  range [50000, 60000): 10,000 keys in 52 page reads
bulk loaded: order 255, height 3, 397 pages, 394 leaves, 254 keys per leaf
  1,000 lookups: 3,000 page reads, 3 per lookup
  range [50000, 60000): 10,000 keys in 42 page reads
order 4 after 10 inserts: height 3
  page 0: leaf [5, 10]
  page 1: leaf [25, 30]
  page 2: node [15, 25] -> pages [0, 4, 1]
  page 3: leaf [35, 40]
  page 4: leaf [15, 20]
  page 5: leaf [45, 50]
  page 6: node [45] -> pages [3, 5]
  page 7: node [35] -> pages [2, 6]
  root is page 7
Output 21.4. 100,000 keys in pages of 4,096 bytes: three levels either way. Random insertion leaves the leaves about three-quarters full, so a range scan reads more leaves than after bulk loading. Below, the order-4 tree of the figure, page by page.

The order comes from the page format: with a 16-byte node header, 8-byte keys and 8-byte page numbers, an internal node names (4096−16)/16=255(4096 - 16)/16 = 255 children. A tree of 100,000 keys therefore has a root, a level of at most 255 nodes and the leaves: every lookup costs 3 page reads, as counted. A range scan descends once and then follows the leaf chain, one page per leaf: 10,000 keys in 52 reads after random insertion, 42 after bulk loading, whose leaves are full.

def chunks(seq, cap):
    """Cut seq into as few pieces of at most cap as possible, of near-equal sizes, so
    that no piece is less than half full."""
    g = -(-len(seq) // cap)
    cuts = [len(seq) * j // g for j in range(g + 1)]
    return [seq[a:b] for a, b in zip(cuts, cuts[1:])]


def bulk_load(items, order, fill=1.0):
    """Build the tree bottom up from sorted (key, value) pairs: leaves, then each
    level of separators, without a single split."""
    t = BPlusTree(order)
    t.nodes, t.writes, level = [], 0, []
    for group in chunks(items, max(1, int((order - 1) * fill))):
        pid = t.new(leaf=True)
        t.nodes[pid].keys = [k for k, _ in group]
        t.nodes[pid].kids = [v for _, v in group]
        if level:
            t.nodes[level[-1][1]].next = pid
        level.append((group[0][0], pid))
    while len(level) > 1:
        upper = []
        for group in chunks(level, max(2, int(order * fill))):
            pid = t.new(leaf=False)
            t.nodes[pid].keys = [k for k, _ in group[1:]]
            t.nodes[pid].kids = [p for _, p in group]
            upper.append((group[0][0], pid))
        level = upper
    t.root = level[0][1] if level else t.new(leaf=True)
    return t
Listing 21.8. Bulk loading: leaves of near-equal size, then each level above, one page write per node. code/bachelor-3/21-database-storage/listings/bptree.py

Deletion is insertion run backwards: a node left below its minimum borrows an entry from a sibling that can spare one, or else merges with a sibling, which removes a key from the parent and may make the parent too small in turn; a root left with a single child is replaced by it, and the tree shrinks at the top. Exercise 21.6 writes it.

21.3 Hash indexes

A B+ tree answers ranges; when only equality is ever asked, a hash index finds a key in about one page read whatever the size of the file.

Definition 21.5 (Static hashing, extendible hashing, linear hashing)

Static hashing sends key kk to bucket h(k) mod Nh(k) \bmod N for a fixed number NN of bucket pages; a full bucket chains overflow pages. Extendible hashing keeps a directory of 2d2^d pointers indexed by the last dd bits of h(k)h(k), the global depth; each bucket has a local depth d′≤dd' \le d, the number of bits its keys share, and is named by 2d−d′2^{d-d'} directory entries. A full bucket splits on bit d′d'; if d′=dd' = d, the directory doubles first. Linear hashing has no directory: buckets split one at a time, in a fixed round-robin order, whenever the load passes a threshold, and a bucket already split in the current round is addressed with one more bit.

Extendible hashing was published by Ronald Fagin, Jurg Nievergelt, Nicholas Pippenger and Raymond Strong in 1979, linear hashing by Witold Litwin in 1980. Neither rehashes the whole file when it grows: a split moves the keys of one bucket only. Extendible hashing pays with a directory, which doubles; linear hashing pays with overflow pages on the buckets whose turn to split has not yet come.

    def put(self, key, value):
        b = self.bucket(key)
        if key in b["items"] or len(b["items"]) < self.cap:
            b["items"][key] = value
            return
        if b["depth"] == self.depth:  # no spare bit: double the directory
            self.dir += self.dir
            self.depth += 1
            self.doublings += 1
        bit = 1 << b["depth"]  # split b on its next bit
        b["depth"] += 1
        new = {"depth": b["depth"], "items": {}}
        for k in [k for k in b["items"] if self.h(k) & bit]:
            new["items"][k] = b["items"].pop(k)
        for i in range(len(self.dir)):
            if self.dir[i] is b and i & bit:
                self.dir[i] = new
        self.splits += 1
        self.put(key, value)  # may split again
Listing 21.9. Extendible hashing: double the directory if needed, then split one bucket on its next bit. code/bachelor-3/21-database-storage/listings/extendible.py
Extendible hashing with buckets of two keys and h(k) = k. Inserting 3 (binary 11) into the full bucket of the keys ending in 1 needs a second bit: the directory doubles, the bucket splits into 01 and 11, and bucket 0, still of local depth 1, is now named by two entries.
Extendible hashing with buckets of two keys and h(k)=kh(k) = k. Inserting 3 (binary 11) into the full bucket of the keys ending in 1 needs a second bit: the directory doubles, the bucket splits into 01 and 11, and bucket 0, still of local depth 1, is now named by two entries.
$ python extendible.py
put  4 = 00100: d = 0     *:[4]
put  9 = 01001: d = 0     *:[4, 9]
put 16 = 10000: d = 1 x2  0:[4, 16] 1:[9]
put  1 = 00001: d = 1     0:[4, 16] 1:[1, 9]
put 25 = 11001: d = 4 x8  0:[4, 16] 0001:[1] 1001:[9, 25] 101:[] 11:[]
put 12 = 01100: d = 4     000:[16] 0001:[1] 10:[] 100:[4, 12] 1001:[9, 25] 101:[] 11:[]
put  7 = 00111: d = 4     000:[16] 0001:[1] 10:[] 100:[4, 12] 1001:[9, 25] 101:[] 11:[7]
put 20 = 10100: d = 4     000:[16] 0001:[1] 0100:[4, 20] 10:[] 1001:[9, 25] 101:[] 11:[7] 1100:[12]
100,000 keys, 64 per bucket: directory 2^11 = 2,048, 2,048 buckets, 11 doublings
Output 21.5. The same keys with eight insertions, each bucket printed once under the bits its keys share. The keys 1, 9 and 25 agree on their last three bits, so inserting 25 doubles the directory three times; a good hash, below, keeps the directory as small as the buckets need.

With h(k)=kh(k) = k, keys that agree on many low bits pile into one bucket and blow the directory up: inserting 25 alone splits three times and multiplies the directory by eight; the eight insertions end with 16 directory entries for 8 buckets. With a multiplicative hash, 100,000 keys in buckets of 64 need 2,048 directory entries and 2,048 buckets: one page read per lookup when the directory is in memory. Exercise 21.11 builds linear hashing.

A hash index cannot answer WHERE out_date > ’2025-06-01’: neighbouring keys land in unrelated buckets. That is why the B+ tree is the default index of almost every database, and a hash index the special case.

21.4 Log-structured merge trees

A B+ tree updates pages in place: each insertion reads a path and writes at least a leaf, a random write. When writes dominate, it is cheaper to write only in large sorted runs, the idea of the log-structured file system of Chapter 12 applied to an index.

Definition 21.6 (Log-structured merge tree, memtable, sorted run, read amplification)

A log-structured merge tree keeps recent writes in a memtable, a sorted structure in memory. A full memtable is written to disk as a sorted run, an immutable file of pairs in key order. Runs are organised in levels 0,1,2,…0, 1, 2, \ldots of growing capacity, each a size ratio TT larger than the one above; compaction (Year 2 volume), here, merges the runs of a level into the next, the newest value of a key winning, and rewrites the result. A lookup searches the memtable, then the levels from the newest; the read amplification is the number of runs, or pages, a lookup reads.

Patrick O’Neil, Edward Cheng, Dieter Gawlick and Elizabeth O’Neil published the structure in 1996. Its price is paid twice. An entry is rewritten at every compaction that touches its level: that is write amplification, here counted in entries. And a lookup may have to look in every level: read amplification. A Bloom filter per run cuts the second, since a run that certainly lacks the key is not read.

    def put(self, key, value):
        self.inserted += 1
        self.mem[key] = value
        if len(self.mem) >= self.C:
            self.push(0, sorted(self.mem.items()))
            self.mem = {}

    def push(self, i, items):
        """Merge items into level i (newer wins), write the level, cascade if over."""
        if i == len(self.levels):
            self.levels.append(None)
        old = self.levels[i]
        merged = dict(zip(old.keys, old.values)) if old else {}
        merged.update(items)
        run = sorted(merged.items())
        self.written += len(run)  # the whole level is rewritten
        if len(run) > self.C * self.T ** (i + 1):
            self.levels[i] = None
            self.push(i + 1, run)
        else:
            self.levels[i] = Run(run)

    def get(self, key):
        if key in self.mem:
            return self.mem[key]
        for run in self.levels:  # newest level first
            if run and run.bloom.may_contain(key):
                self.run_reads += 1
                j = bisect_left(run.keys, key)
                if j < len(run.keys) and run.keys[j] == key:
                    return run.values[j]
        return None
Listing 21.10. A levelled LSM tree: level ii holds at most CTi+1C T^{i+1} entries and is merged down when it overflows. code/bachelor-3/21-database-storage/listings/lsm.py
A levelled LSM tree: each level is one sorted run, T times larger than the level above; a lookup reads at most one run per level, fewer with Bloom filters.
A levelled LSM tree: each level is one sorted run, TT times larger than the level above; a lookup reads at most one run per level, fewer with Bloom filters.
$ python lsm_demo.py
T = 4: levels [0, 0, 40000, 159988]
  200,000 writes, 1,799,971 entries written to disk: write amplification 9.0
  runs read per lookup: 1.01 for present keys, 0.014 for absent keys
T = 10: levels [2000, 87998, 109995]
  200,000 writes, 2,301,967 entries written to disk: write amplification 11.5
  runs read per lookup: 1.01 for present keys, 0.024 for absent keys
Output 21.6. 200,000 random writes. Every entry is written about ten times on its way down; a lookup reads one run when the key is present, and almost never one when it is absent.

Each level holds a single run, rewritten whenever the level above spills into it, so an entry is written once by the flush and then, at each level, about T/2T/2 times more on average; Exercise 21.9 turns this into a bound. The smaller ratio rewrites less per level but needs more levels; with these sizes the two effects net out to a write amplification of 9.0 for T=4T = 4 and 11.5 for T=10T = 10. Absent keys cost 0.014 and 0.024 runs read per lookup, the false-positive rates of filters with 10 bits per key summed over the levels. Each insertion into the B+ tree of the previous section writes at least one whole page, 4,096 bytes for one 16-byte entry: an LSM tree that writes each entry ten times in big sequential runs writes far fewer pages, and Exercise 21.12 counts both.

21.5 Choosing an index

Definition 21.7 (Clustered index, secondary index, covering index)

An index (Year 2 volume) is clustered when the table’s rows themselves are stored in the order of its key, in its leaves or in pages sorted the same way; a table has at most one. A secondary index holds, for each key, the identifiers of the rows, which are stored elsewhere in another order; following them costs about one page read per row. An index is covering for a query when it holds every column the query needs, so the table is not read at all.

SQLite stores each ordinary table as a B-tree keyed by a 64-bit integer, the rowid, with the rows in the leaves: the table is clustered on its rowid, which an INTEGER PRIMARY KEY column names. Each index is another B-tree, holding keys and no other data. Its EXPLAIN QUERY PLAN says how a query will be run: SCAN reads the whole table, SEARCH only part of it, and USING COVERING INDEX means the table is never touched. The format is meant for people and may change between releases.

$ python sqlrun.py plan.sql
sql> SELECT count(*) AS loans FROM loans;
+-------+
| loans |
+-------+
| 400   |
+-------+
(1 row)

sql> EXPLAIN QUERY PLAN SELECT out_date FROM loans WHERE member_id = 41;
+----+--------+---------+------------+
| id | parent | notused | detail     |
+----+--------+---------+------------+
| 2  | 0      | 0       | SCAN loans |
+----+--------+---------+------------+
(1 row)

sql> CREATE INDEX loans_member ON loans(member_id);
OK

sql> EXPLAIN QUERY PLAN SELECT out_date FROM loans WHERE member_id = 41;
+----+--------+---------+-----------------------------------------------------+
| id | parent | notused | detail                                              |
+----+--------+---------+-----------------------------------------------------+
| 3  | 0      | 0       | SEARCH loans USING INDEX loans_member (member_id=?) |
+----+--------+---------+-----------------------------------------------------+
(1 row)

sql> CREATE INDEX loans_member_out ON loans(member_id, out_date);
OK

sql> EXPLAIN QUERY PLAN SELECT out_date FROM loans WHERE member_id = 41;
+----+--------+---------+------------------------------------------------------------------+
| id | parent | notused | detail                                                           |
+----+--------+---------+------------------------------------------------------------------+
| 2  | 0      | 0       | SEARCH loans USING COVERING INDEX loans_member_out (member_id=?) |
+----+--------+---------+------------------------------------------------------------------+
(1 row)

sql> EXPLAIN QUERY PLAN SELECT * FROM loans WHERE out_date > '2025-06-01';
+----+--------+---------+------------+
| id | parent | notused | detail     |
+----+--------+---------+------------+
| 2  | 0      | 0       | SCAN loans |
+----+--------+---------+------------+
(1 row)
Output 21.7. One query on the town’s 400 loans, run against three states of the schema. The last query, on a column with no index, scans.

Without an index, finding member 41’s loans reads the whole table. With an index on member_id, SQLite searches the index and follows each row identifier into the table. With an index on (member_id, out_date), the date is in the index itself and the table is not read. The index on a pair answers questions on its first column alone, but not on its second: a search on out_date scans, as a telephone directory sorted by surname and first name does not help to find every Ada.

Every index has a price: it is written at each insertion, a page or more, and takes space. An index pays when the column is searched often and selects few rows; a query that returns most of a table is cheaper as a scan, since a scan reads each page once while a secondary index may read the same page once per row.

21.6 Exercises

Exercise 21.1 ★

In the slotted page of Listing 21.2, how much free space remains after 30 records of 40 bytes each? After deleting 10 of them, how much is free before and after compact? How many more 40-byte records fit?

Solution

Solution of Exercise 21.1.

The page has 4,096 bytes, a 4-byte header and 4 bytes per slot. After 30 records: 4096−4−30×4−30×40=2,7724096 - 4 - 30 \times 4 - 30 \times 40 = 2{,}772 bytes free. Deleting 10 empties their slots but leaves their bytes in the record area: still 2,772 free. compact slides the 20 live records to the back, so the records start at 4096−800=3,2964096 - 800 = 3{,}296 and 3,296−124=3,1723{,}296 - 124 = 3{,}172 bytes are free. Ten new records reuse the empty slots at 40 bytes each, leaving 2,772; each further record needs 44 bytes with its slot, and 2,772=63×442{,}772 = 63 \times 44: 73 more records, and the page is exactly full.

Exercise 21.2 ★

Give the least and the greatest height of a B+ tree of order 100 holding 10710^7 keys, every node full in the first case, every non-root node at its minimum in the second.

Solution

Solution of Exercise 21.2.

Full nodes: leaves of 99 keys, internal nodes of 100 children. ⌈107/99⌉=101,011\lceil 10^7/99 \rceil = 101{,}011 leaves, then 1,011, 11 and 1 nodes: height 4. Minimal nodes: by Theorem 21.4 with m=100m = 100, h≤1+log⁡50(5×106)≈1+3.94h \le 1 + \log_{50}(5 \times 10^6) \approx 1 + 3.94, so h≤4h \le 4. Least and greatest heights are both 4: every B+ tree of order 100 on 10710^7 keys has height 4.

Exercise 21.3 ★

A buffer pool of 3 frames, empty, runs bufferpool.py’s clock on the page accesses 1, 2, 3, 1, 4, 1, 5, 2, each page unpinned after its access. Say for each access whether it hits or misses, and which page is evicted.

Solution

Solution of Exercise 21.3.

Accesses 1, 2, 3 miss and fill the three frames, each with its reference bit set. The second access to 1 hits. Page 4 misses: every frame is unpinned with its bit set, so the hand clears the three bits in one sweep and comes back to frame 0: page 1 is evicted, although it was used two accesses ago. Page 1 then misses and evicts page 2, the next frame with a clear bit; 5 misses and evicts 3; 2 misses and evicts 4. Seven misses and one hit: when every bit is set the clock degenerates into first in, first out.

Exercise 21.4 ★

exercises/ex4_plans.sql creates the index loans_member on the town’s loans and asks for the plans of SELECT count(*) FROM loans WHERE member_id = 41, SELECT member_id FROM loans WHERE member_id > 100, SELECT book_id FROM loans WHERE book_id = 59 and SELECT * FROM loans WHERE loan_id = 7. Predict each plan line, then run it.

Solution

Solution of Exercise 21.4.

The four plan lines, in order:

  • SEARCH loans USING COVERING INDEX loans_member (member_id=?) Counting needs no column outside the index.
  • SEARCH loans USING COVERING INDEX loans_member (member_id>?) A range in the index, which again holds every column needed.
  • SCAN loans There is no index on book_id.
  • SEARCH loans USING INTEGER PRIMARY KEY (rowid=?) loan_id is the rowid, the key of the table’s own B-tree, so the table is searched directly.

A test checks the four lines.

Exercise 21.5 ★★

exercises/ex5_split.py splits leaves the way internal nodes are split, moving the middle key up. Insert 1 to 10 into its tree of order 4: which keys can no longer be found, and why exactly those? Fix it.

Solution

Solution of Exercise 21.5.

Keys 3, 6 and 9 are lost. A leaf of order 4 overflows at 4 keys [a,b,c,d][a, b, c, d]; the buggy split sends cc up and keeps [a,b][a, b] and [d][d], so cc is in no leaf. A search for cc goes right of the separator cc, into [d][d], and fails. With increasing keys the overflowing leaf is [1,2,3,4][1, 2, 3, 4], then [4,5,6,7][4, 5, 6, 7], then [7,8,9,10][7, 8, 9, 10], and the third key of each is dropped. The fix keeps cc in the right leaf and copies it up: right.keys = n.keys[half:] and the separator right.keys[0], which is split_leaf of Listing 21.7.

Exercise 21.6 ★★

Write delete(tree, key) for bptree.py: a node left below its minimum borrows from a sibling that can spare an entry, or else merges with one; a root with a single child is replaced by it. It is tested against a dictionary, with every invariant of Definition 21.3 checked after each operation, for orders 3 to 7.

Solution

Solution of Exercise 21.6.

exercises/ex6_delete.py deletes from the leaf, then repairs on the way back up: if the child just visited is below its minimum, it tries the left sibling, then the right, for one that stays at or above its minimum after giving an entry away. Borrowing between leaves moves one pair and resets the separator to the first key of the right leaf; between internal nodes it rotates through the parent: the separator comes down into the child and the sibling’s end key goes up. Otherwise the child merges with a sibling: for leaves the keys are concatenated and the leaf chain relinked; for internal nodes the separator comes down between the two key lists. The parent loses one key and one child and may be repaired in turn by its own parent. Finally a root with one child is replaced by that child. The test runs random insertions and deletions for orders 3 to 7 and checks after each operation that keys are sorted and bounded by the separators, that every leaf is at one depth and that every non-root node is at its minimum.

Exercise 21.7 ★★

Prove that a B+ tree of order mm with nn keys has at least 1+⌈log⁡m(n/(m−1))⌉1 + \lceil \log_m (n/(m-1)) \rceil levels. With the bound of Theorem 21.4, how many heights are possible for n=106n = 10^6 and m=255m = 255?

Solution

Solution of Exercise 21.7.

Facts used: an internal node has at most mm children and a leaf at most m−1m - 1 keys.

A tree of hh levels has at most mh−1m^{h-1} leaves, so n≤mh−1(m−1)n \le m^{h-1}(m-1) and h≥1+log⁡m(n/(m−1))h \ge 1 + \log_m (n/(m-1)); hh being an integer, h≥1+⌈log⁡m(n/(m−1))⌉h \ge 1 + \lceil \log_m (n/(m-1)) \rceil. For n=106n = 10^6 and m=255m = 255: log⁡2553,937≈1.49\log_{255} 3{,}937 \approx 1.49, so h≥3h \ge 3. The upper bound, with ⌈255/2⌉=128\lceil 255/2 \rceil = 128 and ⌈254/2⌉=127\lceil 254/2 \rceil = 127, is h≤2+log⁡128(106/254)≈2+1.71h \le 2 + \log_{128}(10^6/254) \approx 2 + 1.71, so h≤3h \le 3. Only height 3 is possible, as both lines of Output 21.8 show.

Exercise 21.8 ★★

Count the page reads of a range scan returning kk keys from a tree of height hh whose leaves hold ℓ\ell keys each. Explain the 42 reads of Output 21.4, and what the 52 after random insertion say about the leaves in that range.

Solution

Solution of Exercise 21.8.

The descent reads h−1h - 1 internal nodes; then each leaf touched costs one read. A range of kk keys starting anywhere in a leaf spans at least ⌈k/ℓ⌉\lceil k/\ell \rceil leaves and at most ⌈k/ℓ⌉+1\lceil k/\ell \rceil + 1, and the scan may read one more leaf to see the first key beyond the range. So h−1+⌈k/ℓ⌉≤reads≤h+1+⌈k/ℓ⌉h - 1 + \lceil k/\ell \rceil \le \text{reads} \le h + 1 + \lceil k/\ell \rceil. Bulk loading put about 254 keys in each leaf: 10,000/254≈39.410{,}000/254 \approx 39.4, and 2+40=422 + 40 = 42. After random insertion, 52=2+5052 = 2 + 50: the range spans 50 leaves, about 200 keys each, 79 % full there, against 189 on average over the tree.

Exercise 21.9 ★★

For lsm.py with memtable size CC and ratio TT, show that level 0 writes (T+2)/2(T+2)/2 entries per entry it receives and each lower level about (T+1)/2(T+1)/2. Deduce that the write amplification of a tree with LL levels is at most about L(T+2)/2L(T+2)/2, and compare with Output 21.6.

Solution

Solution of Exercise 21.9.

Facts used: in push, a level is rewritten whole each time something is merged into it, and it is pushed down as soon as it holds more than CTi+1C T^{i+1} entries.

Level 0 receives memtables of CC entries and is rewritten at sizes C,2C,…,(T+1)CC, 2C, \ldots, (T+1)C, the last being pushed down: C(T+1)(T+2)/2C(T+1)(T+2)/2 entries written for (T+1)C(T+1)C received, (T+2)/2(T+2)/2 each. Level i≥1i \ge 1 receives batches of a size bb just above CTiC T^i, and overflows once it holds more than CTi+1C T^{i+1}, after about TT batches; it is written at sizes b,2b,…,Tbb, 2b, \ldots, Tb, which is bT(T+1)/2b T(T+1)/2 for TbT b received, (T+1)/2(T+1)/2 each. An entry that has gone down LL levels has been written at most about (T+2)/2+(L−1)(T+1)/2≤L(T+2)/2(T+2)/2 + (L-1)(T+1)/2 \le L(T+2)/2 times. For T=4T = 4 with four levels the bound is 12, measured 9.0; for T=10T = 10 with three levels it is 18, measured 11.5. The measurements are lower because the bottom level is not full: most entries have been through only part of its cycle.

Exercise 21.10 ★★★

Prove that bulk_load builds a valid B+ tree, with every non-root node at its minimum or above, in at most 2n/⌊m/2⌋+22n/\lfloor m/2 \rfloor + 2 page writes for nn keys, O(n/m)O(n/m).

Solution

Solution of Exercise 21.10.

Facts used: chunks(seq, cap) cuts ss items into g=⌈s/cap⌉g = \lceil s/\text{cap} \rceil pieces whose sizes are ⌊s/g⌋\lfloor s/g \rfloor or ⌈s/g⌉\lceil s/g \rceil.

Sizes. Each piece has at most ⌈s/g⌉≤cap\lceil s/g \rceil \le \text{cap} items. When g≥2g \ge 2, g−1<s/capg - 1 < s/\text{cap} gives s/g>cap(g−1)/g≥cap/2s/g > \text{cap}(g-1)/g \ge \text{cap}/2, so each piece has more than half the capacity: leaves (cap m−1m - 1) get at least ⌈(m−1)/2⌉\lceil (m-1)/2 \rceil pairs and internal nodes (cap mm) at least ⌈m/2⌉\lceil m/2 \rceil children. When g=1g = 1, the single piece is the root, which needs only 2 children, and the loop builds internal nodes only while a level has at least 2 nodes.

Order. Leaves are filled from the sorted pairs in order and chained in order. The separators of an internal node are the smallest keys of its children after the first, so child jj’s keys lie between separator j−1j - 1 and separator jj. Each level is built from the whole level below, so all leaves are at the same depth.

Cost. Every node is written once. There are at most n/⌈(m−1)/2⌉+1≤n/⌊m/2⌋+1n/\lceil (m-1)/2 \rceil + 1 \le n/\lfloor m/2 \rfloor + 1 leaves, and since every internal node has at least 2 children there are fewer internal nodes than leaves: at most 2n/⌊m/2⌋+22n/\lfloor m/2 \rfloor + 2 page writes, O(n/m)O(n/m), all sequential and with no split.

Exercise 21.11 ★★★

Implement linear hashing as a class LinearHash with put and get, NN initial buckets, a capacity per primary page, and a split of the next bucket in round-robin order whenever the load passes a threshold. It is tested against a dictionary. Why is the bucket that splits usually not the one that overflowed, and what does it cost?

Solution

Solution of Exercise 21.11.

exercises/ex11_linear.py: address computes h mod N2Lh \bmod N 2^L and, if the result is below next, the bucket has already split this round and h mod N2L+1h \bmod N 2^{L+1} is used. put inserts and, while the load exceeds the threshold, splits bucket next: its keys are rehashed with one more bit into it and a new bucket at the end, next advances, and when every bucket of the round has split the level rises and next returns to 0. The bucket that splits is the next in line, not the full one, because that is what lets the address be computed from two numbers, the level and next, without a directory. The cost is that an overflowing bucket chains overflow pages until its turn comes, at most one round later: lookups in it read more than one page meanwhile. The test checks get against a dictionary and that the load stays under the threshold.

Exercise 21.12 ★★★

Run 100,000 operations on the B+ tree of order 255 and on the LSM tree with C=1000C = 1000 and T=10T = 10, once with 90 % reads and once with 10 % reads, counting page reads and writes (for the LSM tree, one page read per run searched and one page written per 254 entries). Which wins, by how much, and what does the count leave out?

Solution

Solution of Exercise 21.12.

exercises/ex12_workload.py prints, in page I/O per operation, 2.07 for the B+ tree and 0.72 for the LSM tree with 90 % reads, and 3.38 against 0.13 with 10 % reads. The LSM tree wins both, by 3 times and by 26 times. The count favours it in several ways. It gives the B+ tree no buffer pool, though its root and second level, 1 MiB at most, would be cached and a lookup would cost one read. It assumes each run’s index and Bloom filter are in memory. It counts the LSM tree’s sequential writes like random ones, which favours the B+ tree on a disk. And it leaves out range scans, which in an LSM tree must merge every level. With the top levels cached, the B+ tree reads one page per lookup, close to the LSM tree’s 1.01 for present keys; for writes, the LSM tree’s advantage remains.

21.7 Weekend problem

Problem 21.1

Weekend problem — How tall is the town archive’s index?

The town archive wants one index over every document it will ever hold, keyed by an 8-byte number, in pages of 4,096 bytes. This problem computes how tall a B+ tree it needs, measures one, and asks what caching the top levels buys.

PAGE, HEADER, KEY, PTR = 4096, 16, 8, 8
FANOUT = (PAGE - HEADER) // (KEY + PTR)  # children of an internal node
LEAF = FANOUT - 1  # entries of a leaf (key + 8-byte value)


def height(n, fill):
    """Levels needed for n keys when every node is filled to `fill`."""
    leaf, fan = int(LEAF * fill), int(FANOUT * fill)
    nodes, h = -(-n // leaf), 1
    while nodes > 1:
        nodes, h = -(-nodes // fan), h + 1
    return h
Listing 21.11. The order from the page format, and the height for nn keys at a given fill. code/bachelor-3/21-database-storage/listings/archive.py
$ python archive.py
fan-out 255, 254 entries per leaf
        1,000,000 keys: height 3 full, 3 at 69 % fill, 3 half full
    1,000,000,000 keys: height 4 full, 5 at 69 % fill, 5 half full
1,000,000,000,000 keys: height 5 full, 6 at 69 % fill, 6 half full
random inserts: height 3, 5,705 pages, leaf fill 69%, 3 reads per lookup
bulk loaded: height 3, 3,955 pages, leaf fill 100%, 3 reads per lookup
0 top level(s) cached, 0 pages = 0.0 MiB: 3 page read(s) per lookup
1 top level(s) cached, 1 pages = 0.0 MiB: 2 page read(s) per lookup
2 top level(s) cached, 17 pages = 0.1 MiB: 1 page read(s) per lookup
3 top level(s) cached, 3,955 pages = 15.4 MiB: 0 page read(s) per lookup
Output 21.8. Heights from the formula, the measured million-key trees, and the cost of a lookup with the top levels in the buffer pool.

Part I — Fan-out.

  1. An internal node has a 16-byte header, keys of 8 bytes and child page numbers of 8 bytes. How many children fit in a page?
  2. Check that 255 children fit and 256 do not, counting keys and pointers exactly.
  3. A leaf stores (key, value) pairs of 16 bytes, its header and an 8-byte pointer to the next leaf. How many pairs fit?
  4. What would the fan-out be with 4-byte keys and 4-byte page numbers?
  5. Why does a wider node make the tree shorter but not a binary search inside it slower in page reads?
  6. SQLite’s page header is 8 or 12 bytes. Why can a real database not quite reach the fan-out of question 1?

Part II — Heights.

  1. Compute the number of leaves and of nodes at each level for 10910^9 full leaves and nodes, and the height.
  2. Do the same for 10610^6 keys.
  3. For 101210^{12} keys, find the height without computing every level.
  4. At 69 % fill, why does a billion keys take one more level?
  5. What is the largest number of keys a tree of height 4 can hold?
  6. Apply Theorem 21.4 to bound the height of 10910^9 keys in the worst case. Compare with the half-full line of Output 21.8.

Part III — Measured.

  1. Explain the 3,955 pages of the bulk-loaded million-key tree.
  2. The tree built by random insertion has 5,705 pages and leaves 69 % full. Where do the empty quarters come from?
  3. Why do both trees cost 3 reads per lookup in spite of their different sizes?
  4. How many pages does the random tree waste, and how much space is that?
  5. Inserting the keys in increasing order into BPlusTree gives leaves only half full. Why, with this split?
  6. How could a database avoid that half-full tree when keys arrive in order?

Part IV — Caching.

  1. Explain the four cache lines of Output 21.8.
  2. For a billion keys in full nodes, how much memory keeps the top two levels, and the top three?
  3. What does a lookup cost in each case?
  4. Suppose a disk serves one random page read in 5 ms. How many lookups per second can it serve with nothing cached, with two levels cached and with three?
  5. Why is caching the top levels almost free while caching the leaves is not?
  6. Sum up: how tall is the archive’s index for a billion documents, and what does a lookup cost?
Solution

Solution of Problem 21.1.

1. ⌊(4096−16)/16⌋=255\lfloor (4096 - 16)/16 \rfloor = 255.

2. 255 children need 254 keys: 254×8+255×8+16=4,088≤4,096254 \times 8 + 255 \times 8 + 16 = 4{,}088 \le 4{,}096. 256 children need 255×8+256×8+16=4,104>4,096255 \times 8 + 256 \times 8 + 16 = 4{,}104 > 4{,}096.

3. ⌊(4096−16−8)/16⌋=254\lfloor (4096 - 16 - 8)/16 \rfloor = 254, the LEAF of Listing 21.11.

4. (4096−16)/8=510(4096 - 16)/8 = 510 children: twice as wide, and each level holds twice as many keys.

5. The node is one page read whatever its width; the binary search inside it runs in memory, about log⁡2255≈8\log_2 255 \approx 8 comparisons, costing nanoseconds against the milliseconds or microseconds of a page read.

6. A real page also holds a slot or cell-pointer array, variable-length keys with their own length fields, and free space left for later insertions, so fewer entries fit than in this fixed layout.

7. ⌈109/254⌉=3,937,008\lceil 10^9/254 \rceil = 3{,}937{,}008 leaves; above them 15,440 nodes, then 61, then the root: height 4.

8. 3,938 leaves, 16 nodes, the root: height 3.

9. About 3.94×1093.94 \times 10^9 leaves; 2553≈1.66×107255^3 \approx 1.66 \times 10^7 is too few to name them and 2554≈4.23×109255^4 \approx 4.23 \times 10^9 is enough, so four levels above the leaves: height 5.

10. At 69 % a leaf holds 175 pairs and a node 175 children: 5,714,286 leaves, more than 1753=5,359,375175^3 = 5{,}359{,}375, so a fourth internal level is needed: height 5.

11. 2553255^3 leaves of 254 pairs: 4,211,669,250 keys.

12. With ⌈255/2⌉=128\lceil 255/2 \rceil = 128 and ⌈254/2⌉=127\lceil 254/2 \rceil = 127: h≤2+log⁡128(109/254)≈2+3.13h \le 2 + \log_{128}(10^9/254) \approx 2 + 3.13, so h≤5h \le 5. The half-full line of Output 21.8, with nodes at 127 entries, gives 5 as well.

13. 3,938+16+1=3,9553{,}938 + 16 + 1 = 3{,}955: question 8’s levels.

14. A leaf splits into two half-full leaves, which fill up again before they split: at any moment the leaves are spread between half full and full. The average is about 69 %, as measured.

15. A lookup reads one page per level, and both trees have three: the extra 1,750 pages are spread across the leaf level and the level above, which stays below 255 nodes.

16. 5,705−3,955=1,7505{,}705 - 3{,}955 = 1{,}750 pages, 7,168,000 bytes, about 6.8 MiB: 44 % more space.

17. Increasing keys always go to the last leaf. When it splits, its left half keeps ⌊255/2⌋=127\lfloor 255/2 \rfloor = 127 pairs and never receives another key, so every leaf but the last ends half full; a test counts 127 in each.

18. Split a leaf unevenly when the new key is the largest in the tree, keeping all but one pair on the left; or, when all the keys are known in advance, bulk load them.

19. The bulk-loaded tree has levels of 1, 16 and 3,938 pages. Nothing cached: 3 reads. The root cached: 2. The root and the 16 nodes, 17 pages, 68 KiB: 1. All 3,955 pages, 15.4 MiB: none.

20. The top two levels are 1+61=621 + 61 = 62 pages, 248 KiB; the top three are 62+15,440=15,50262 + 15{,}440 = 15{,}502 pages, about 60.6 MiB.

21. 4 page reads with nothing cached, 2 with two levels cached, 1 with three.

22. 200 reads per second: 50 lookups per second with nothing cached, 100 with two levels, 200 with three.

23. Each level is about 255 times smaller than the level below it: the leaves are 3,937,0083{,}937{,}008 of the 3,952,5103{,}952{,}510 pages, 99.6 %. Caching everything above them costs 0.4 % of the index; caching the leaves costs the rest.

24. With full nodes, a billion documents need a B+ tree of height 4; grown by random insertion, its 69 % leaves make it 5. A lookup costs at most 4 page reads in the first case, 2 with 248 KiB of top levels in the buffer pool and 1 with 61 MiB.

本章定义的术语

在术语表中查看全部 1050 个术语