Sub topic 13
Combining filters: union and its caveats
This chapter assumes you have read the earlier chapters on insertion, lookup, sizing, and double hashing. You should be comfortable with bitwise OR and AND on bytes. Here you will see how to merge two Bloom filters, when that is safe, and why the result can quietly get worse.
Why union works
A Bloom filter stores an item by setting k bits. A lookup passes only if all k bits are set. Setting a bit never clears another bit, so the order of insertions does not matter.
Take two filters, A and B. Set each bit in the result if it is set in A or in B. Every item added to either filter still has all of its bits set, so it still passes. The result is the same as if you had inserted both sets of items into one filter. This is a bitwise OR.
Compatibility rules
The OR only makes sense if both filters map items to bit positions in the same way. Check that both filters have:
- the same number of bits, m
- the same number of hash functions, k
- the same hash function and the same seeds or salts
If any of these differ, the same item sets different bits in each filter. The OR then produces a filter that can miss items, which is a false negative. Reject mismatched filters instead of guessing.
Implementation
This example uses the class from the earlier chapters. The union function returns a new filter and leaves both inputs unchanged.
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))
def estimated_fpr(self):
set_bits = sum(bin(byte).count("1") for byte in self.bits)
return (set_bits / self.m) ** self.k
def union(a, b):
if a.m != b.m or a.k != b.k:
raise ValueError("filters must have the same m and k")
result = BloomFilter.__new__(BloomFilter)
result.m, result.k = a.m, a.k
result.bits = bytearray(x | y for x, y in zip(a.bits, b.bits))
return result
a = BloomFilter(1000, 0.01)
b = BloomFilter(1000, 0.01)
for i in range(1000):
a.add(f"a-{i}")
b.add(f"b-{i}")
u = union(a, b)
print(u.might_contain("a-5"), u.might_contain("b-5")) # True True
print(round(a.estimated_fpr(), 3)) # about 0.01
print(round(u.estimated_fpr(), 3)) # about 0.16The estimated_fpr method uses the fraction of set bits. A random non-member passes when all k probed bits are set, so the false positive rate is about (fraction set)^k.
The main caveat: the union fills up
The union holds the items of both filters, but it still has only m bits. Each filter was sized for 1,000 items at 1%. The union holds up to 2,000 items, so about 77% of its bits are set instead of about 50%. The false positive rate rises from 1% to about 16%.
Plan for this before you merge. Either size each filter for the combined item count, or accept a higher error rate. If the two sets overlap, the result is somewhat better than the worst case, but you cannot tell by how much without the original items.
Intersection is not safe
You can AND two filters, but the result is not the filter of the intersection. A bit can be set in both filters because different items set it. The AND therefore has extra set bits, and its false positive rate is higher than a filter built directly from the common items. It still has no false negatives for items in both sets, so treat it only as a rough, pre-filtering approximation.
Practical uses
Union lets several workers each build a filter over their own data and then merge the filters, which is a cheap way to parallelize construction. Distributed systems also send filters between nodes and OR them together. In both cases, agree on m, k, and the hash scheme up front.
Exercise
Filter A has m = 9586 bits and k = 7. Filter B has m = 19171 bits and k = 7. Can you OR them to get a valid union? What would you do instead?
Show answer
No. The two filters have different m, so the same item maps to different positions in each filter (positions are taken modulo m), and an OR would cause false negatives. Rebuild both filters with the same m and k, sized for the combined number of items, and then OR them.