Sub topic 4
Inserting items and checking membership
This chapter assumes you can read basic Python, know what a hash function does, and can use bitwise operators (|, &, <<). Earlier chapters introduced the bit array and hash functions. Here you combine them into the two operations every Bloom filter supports: insert and query.
The two operations
A Bloom filter has an array of m bits, all starting at 0, and k hash functions. Each hash function maps an item to a position between 0 and m-1.
- Insert: compute the item's
kpositions and set each of those bits to 1. - Query: compute the same
kpositions. If every bit is 1, answer "possibly in the set". If any bit is 0, answer "definitely not in the set".
Both operations touch exactly k bits, so their cost does not depend on how many items are stored.
A small trace
Take m = 16 and k = 3. Suppose the hashes send "apple" to positions 2, 7 and 11, and "banana" to positions 4, 7 and 13. These numbers are made up to show the idea.
- Insert
"apple": bits 2, 7 and 11 become 1. - Insert
"banana": bits 4, 7 and 13 become 1. Bit 7 was already 1 and stays 1. - Query
"apple": bits 2, 7 and 11 are all 1, so the answer is "possibly in the set". - Query
"cherry", which maps to 1, 7 and 9: bit 1 is 0, so the answer is "definitely not in the set".
Notice that bit 7 is shared. A bit does not record which item set it. This sharing is what makes the filter small, and it is also the source of the errors covered in later chapters.
The implementation
The class below stores the bits in a bytearray. Position pos lives in byte pos // 8, at bit pos % 8 within that byte.
import hashlib
import math
class BloomFilter:
def __init__(self, expected_items, false_positive_rate):
self.m = math.ceil(-expected_items * math.log(false_positive_rate) / (math.log(2) ** 2))
self.k = max(1, round((self.m / expected_items) * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
digest = hashlib.sha256(item.encode("utf-8")).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for pos in self._positions(item):
self.bits[pos // 8] |= 1 << (pos % 8)
def might_contain(self, item):
return all(self.bits[pos // 8] & (1 << (pos % 8)) for pos in self._positions(item))
bf = BloomFilter(expected_items=1000, false_positive_rate=0.01)
for word in ["apple", "banana", "cherry"]:
bf.add(word)
print(bf.might_contain("apple")) # True: added items are always found
print(bf.might_contain("durian")) # almost certainly False, but True is possible (a false positive)Three details matter:
_positionsis the only place hashing happens, soaddandmight_containare guaranteed to use identical positions. The method turns one SHA-256 digest intokpositions (a later chapter explains this double hashing trick).adduses|=to set a bit without disturbing the other bits in its byte.might_containusesall(...), which stops at the first zero bit. The expressionself.bits[...] & (1 << ...)is nonzero when the bit is set and 0 otherwise, whichalltreats as true or false.
Common errors
- Hashing differently on insert and query. If the two operations use different hash functions, different seeds, or a different
m, added items will be reported as absent. Always derive positions from one shared function. - Using Python's built-in
hash()for strings. It is randomized per process, so a filter saved to disk and reloaded in a new process gives wrong answers. Use a stable hash such as SHA-256. - Treating
Trueas proof. A positive answer should lead to a real lookup if correctness matters. - Inserting far more than
expected_items. The filter keeps working, but more bits become 1 and wrong "possibly" answers become more frequent.
Exercise
A Bloom filter has m = 16 and k = 3. Items X and Y have been inserted. A query for item Z maps to positions 3, 5 and 9. Bits 3 and 5 are 1, and bit 9 is 0. What does the filter answer, and how sure is that answer?
Show answer
It answers "definitely not in the set". Any 0 bit among Z's positions proves Z was never inserted, because inserting Z would have set all three bits. Bits 3 and 5 were set by other items.