Sub topic 11
Range scans with merging iterators
This chapter assumes you know the read path from the previous chapters: a key may live in the memtable or in several SSTables, and newer sources win. It also assumes you can read short Python programs and know what a heap is.
Why scans are harder than point lookups
A point lookup can stop at the first source that has the key. A range scan, such as "all keys from b up to but not including m", cannot. Keys in the range are spread across the memtable and every SSTable. Each source is sorted, but no single source holds the full answer.
Bloom filters also help little here. A filter answers "might this exact key be present?", not "does this file overlap the range?". A scan must check every source whose key range overlaps the query.
The merging iterator
The standard solution is a k-way merge:
- Open one iterator per source, positioned at the first key greater than or equal to the start key. Sorted arrays and block indexes make this a binary search.
- Put each iterator's current entry in a min-heap ordered by key, then by source age (newest first).
- Pop the smallest entry and advance that source's iterator.
- If the key equals the one just emitted, discard the entry. It is an older version of a key already handled.
- If the winning entry is a tombstone, emit nothing. Otherwise emit the pair.
- Stop when the smallest key reaches the end of the range.
A working implementation
Sources are sorted lists of (key, value) pairs, newest first. The age index breaks ties so the heap never compares values or iterators.
import bisect
import heapq
TOMBSTONE = object()
def merge_scan(sources, start, end):
"""Yield (key, value) for start <= key < end. Sources are newest first."""
heap = []
for age, items in enumerate(sources):
it = iter(items[bisect.bisect_left(items, (start,)):])
first = next(it, None)
if first is not None:
heapq.heappush(heap, (first[0], age, first[1], it))
last_key = None
while heap:
key, age, value, it = heapq.heappop(heap)
nxt = next(it, None)
if nxt is not None:
heapq.heappush(heap, (nxt[0], age, nxt[1], it))
if key >= end:
return
if key == last_key:
continue # older version of a key already handled
last_key = key
if value is not TOMBSTONE:
yield key, value
newer = [("b", TOMBSTONE), ("d", "new")]
older = [("a", 1), ("b", 2), ("d", 4), ("e", 5)]
print(list(merge_scan([newer, older], "a", "e")))This prints [('a', 1), ('d', 'new')]. The tombstone for b hides the older value, d shows its newest version, and e is excluded because the end key is exclusive.
Costs and common errors
- Cost grows with source count. Each emitted key costs about
log(k)heap work forksources. Compaction reducesk, which is one reason it helps reads. - Tombstones are consumed, not skipped early. A scan over a heavily deleted range still reads every tombstone and every shadowed value. Many tombstones can make a scan slow even when it returns few rows.
- Wrong tie-breaking. If the heap orders equal keys by anything other than age, an old value can be emitted instead of the newest one.
- Forgetting the end bound. Without the check, the scan runs to the end of the data.
Exercise
A scan runs over a range where the newest source holds a tombstone for key k and an older SSTable holds a value for k. Which entry does the heap pop first, and what does the scan output for k?
Show answer
The heap pops the tombstone first, because ties on key are broken by source age and the newest source wins. The scan marks k as handled, discards the older value when it pops, and outputs nothing for k.