Sub topic 2
Hash functions: mapping items to positions
This chapter assumes you can read basic Python, know what a hash table is, and understand the % (modulo) operator. A Bloom filter relies on hash functions, so we cover what it needs from them here. The bit array and the insert and query steps come in later chapters.
What the filter needs from a hash function
A hash function takes an input, such as a string, and returns a fixed-size number. A Bloom filter uses that number to choose a position in its bit array. Three properties matter:
- Deterministic: the same item always gives the same number. Without this, a lookup could not find the positions that an insert used.
- Uniform: outputs spread evenly over all positions. If some positions are chosen more often, they fill up sooner and the error rate rises.
- Independent-looking: the k hash functions should not agree with each other. If two of them often pick the same position for an item, that item uses fewer distinct bits than intended.
A cryptographic hash such as SHA-256 meets all three well. It is slower than non-cryptographic hashes such as MurmurHash, but it is easy to use from the Python standard library.
From a hash value to a position
A hash value is a very large integer, and the bit array has only m positions. Taking the remainder after dividing by m gives a valid index from 0 to m - 1:
position = hash_value % m
A Bloom filter uses k hash functions, so each item maps to k positions, not one. The positions may occasionally coincide. That is allowed. It just means the item sets fewer than k distinct bits.
A first version: seeded hashing
The simplest way to get k different hash functions is to put a different seed in front of the item before hashing it. This function returns the k positions for one item.
import hashlib
def positions(item, k, m):
result = []
for seed in range(k):
data = f"{seed}:{item}".encode("utf-8")
digest = hashlib.sha256(data).digest()
value = int.from_bytes(digest[:8], "big")
result.append(value % m)
return result
print(positions("apple", 3, 100))
print(positions("apple", 3, 100))
print(positions("banana", 3, 100))The first two lines of output are identical, which shows determinism. The third line is a different list of three positions, because a different item produces different hashes. The exact numbers depend on SHA-256, so run it to see them.
Each position is in the range 0 to 99, because m is 100 here.
Common errors
- Using Python's built-in
hash()on strings. Python randomizes string hashes for each process by default. A filter saved to disk and loaded by a new process would compute different positions and report false negatives. Use a stable hash such ashashlib, or a fixed-seed library hash. - Hashing mutable or ambiguous input. Convert items to bytes in one fixed way, for example UTF-8. Hashing the integer
1and the string"1"without a rule can give inconsistent results between writers and readers. - Weak hashes. A simple hash such as "sum of character codes" sends
"abc"and"cba"to the same value. Clustered outputs break the uniformity assumption behind the error-rate estimates later in this tutorial.
Exercise
A filter has m = 64 bits and k = 2. An item's two hash values are 1000 and 2090. Which positions does it map to, and why must the same item always give the same positions?
Show answer
1000 % 64 = 40 and 2090 % 64 = 42, so the positions are 40 and 42. The same item must always map to the same positions because a lookup checks the bits an earlier insert set. If the positions changed, a lookup could miss an item that was added.