Bloom Filters
In short: a Bloom filter is m bits plus k hash functions. Inserting a key sets
its k positions; querying checks them, and if any is still 0 the key was
definitely never inserted, while all-1s means "maybe". Insert and query both cost O(k)
time, and the whole filter costs O(m) space, about 10 bits per key for a 1%
false-positive rate — far less than storing the keys themselves. It can never produce a
false negative, because nothing ever clears a bit, but it can be fooled into a false
positive once enough other keys have filled in the same positions.

Quarry writes records into segment files on disk. Looking a record up means asking each segment "do you have it?", and each question costs a disk read. That's fine when the answer is yes. It's pure waste when the answer is no, and most answers are no: a key lives in one segment, not in the twenty others you'd have to rule out.
What Quarry wants is a tiny in-memory summary per segment that can say "definitely not here" without touching the disk. It's allowed to sometimes say "maybe" wrongly, since that only costs a wasted read, but it must never say "not here" about a key that is there, because that would lose data. A Bloom filter is exactly that. It's a row of bits plus a few hash functions, and it costs about 10 bits per key for a 1% false-positive rate, however long the keys are.
How it works
A Bloom filter is an array of m bits, all 0 at the start, and k hash functions that
each map a key to a position in 0 … m − 1.
- Insert a key: compute its
kpositions and set those bits. - Query a key: compute the same
kpositions. If any of those bits is 0, the key was never inserted. That's a certain "no". If all are 1, the answer is "maybe". The bits might have been set by other keys.
Step through a 16-bit filter with k = 3. Three records go in, then two lookups
happen, one of which is fooled:
Inserts only ever set bits. A query stops at the first 0 it finds, and it can be fooled only when other keys have set every one of its bits.
Insert rec-11. Its three hashes land on 4, 3 and 2, so those bits are set. 16 cells.
Two facts fall out of this picture:
- No false negatives. An inserted key's bits were set, and nothing ever clears a bit, so its query always finds all ones.
- False positives grow as the filter fills. The more bits are 1, the likelier a
random key's
kprobes all land on ones.
bits = 0
for p in (3, 9, 3):
bits |= 1 << p
print(bin(bits).count("1"), bits >> 9 & 1)