Sub topic 13
Bloom filters for equality lookups
This chapter assumes you know what row groups, column chunks, and the footer are. It also assumes you know how min/max statistics let a reader skip row groups, and that you can read basic Python. Here you will see where those statistics fail and how a Bloom filter covers the gap.
The problem min/max cannot solve
Min/max statistics work well when values are clustered, such as timestamps in an append-only log. They work badly on a column like user_id when rows arrive in random order. Every row group then contains a spread of ids from the whole range, so every row group's [min, max] interval covers almost any value you might look for.
The following script shows this with PyArrow:
import random
import pyarrow as pa
import pyarrow.parquet as pq
random.seed(7)
ids = random.sample(range(10_000_000), 1_000_000)
pq.write_table(
pa.table({"user_id": ids}),
"users.parquet",
row_group_size=100_000,
)
md = pq.ParquetFile("users.parquet").metadata
target = ids[123_456]
candidates = 0
for i in range(md.num_row_groups):
stats = md.row_group(i).column(0).statistics
if stats.min <= target <= stats.max:
candidates += 1
print(candidates, "of", md.num_row_groups, "row groups cannot be skipped")The script prints 10 of 10 row groups cannot be skipped. Only one row group actually holds the target id, but statistics cannot tell which one. A query such as user_id == 4_242_424 must read all ten column chunks.
Sorting the file by user_id would fix this, but you can sort by only one column at a time. Equality lookups on several high-cardinality columns (user id, session id, order id, device id) need a different tool.
What a Bloom filter is
A Bloom filter is a small bit array that answers one question: "Is this value in the set?" It has two possible answers.
- Definitely not present. The reader can skip the row group.
- Possibly present. The reader must read the data to confirm.
A Bloom filter never gives a false negative. If a value was added, the filter always says "possibly present". It can give false positives, where the filter says "possibly" for a value that was never added. A false positive costs one unnecessary read, so it never returns wrong rows.
The filter works like this:
- To add a value, hash it several times. Each hash selects a bit position, and you set those bits to 1.
- To test a value, hash it the same way. If any selected bit is 0, the value was never added. If all are 1, it might have been.
The following pure-Python sketch shows the mechanism. It is a teaching model, not the exact format Parquet uses.
import hashlib
class BloomFilter:
def __init__(self, num_bits: int, num_hashes: int):
self.m = num_bits
self.k = num_hashes
self.bits = bytearray((num_bits + 7) // 8)
def _positions(self, value: int):
digest = hashlib.blake2b(str(value).encode(), digest_size=16).digest()
h1 = int.from_bytes(digest[:8], "little")
h2 = int.from_bytes(digest[8:], "little") | 1
for i in range(self.k):
yield (h1 + i * h2) % self.m
def add(self, value: int) -> None:
for p in self._positions(value):
self.bits[p // 8] |= 1 << (p % 8)
def might_contain(self, value: int) -> bool:
return all(self.bits[p // 8] & (1 << (p % 8)) for p in self._positions(value))
n = 100_000
bf = BloomFilter(num_bits=10 * n, num_hashes=7) # 10 bits per value
for v in range(0, 2 * n, 2): # add the even numbers
bf.add(v)
assert all(bf.might_contain(v) for v in range(0, 2 * n, 2)) # no false negatives
false_positives = sum(bf.might_contain(v) for v in range(1, 2 * n, 2))
print(f"false positive rate: {false_positives / n:.4f}")With 10 bits per value and 7 hashes, the false positive rate comes out near 0.008, which is about 0.8%. The assertion confirms that every value added is found.
How Parquet implements it
Parquet defines a split block Bloom filter (SBBF). It differs from the classic version above in ways that make it fast on CPUs.
- The filter is divided into 256-bit blocks, each made of eight 32-bit words.
- A value is hashed once with xxHash64. The hash picks one block, and then eight bits are set or tested inside that block, one per word.
- Because every lookup touches a single 32-byte block, a test costs one cache line and can use SIMD instructions.
A filter is stored per column chunk, so each row group has its own filter for each column that has one. The column chunk metadata in the footer records the filter's offset (and, in newer files, its length). The filter bytes sit outside the data pages, so a reader that does not use Bloom filters ignores them.
Choosing the filter size
The size of a filter depends on how many distinct values the column chunk holds and on the false positive rate you accept. The Parquet specification gives approximate bits needed per distinct value:
| Target false positive rate | Bits per distinct value |
|---|---|
| 10% | 6.0 |
| 1% | 10.5 |
| 0.1% | 16.9 |
| 0.01% | 26.4 |
For a row group of 100,000 distinct ids at 1%, the filter takes about 131 KB. Compare that with the column chunk itself, which holds hundreds of KB to several MB of compressed ids. The filter is small, but you pay it on every row group of every filtered column.
The count that matters is the number of distinct values, not rows. A column with 4 distinct values in a row group needs a tiny filter. A column that is unique per row needs the most. Writers usually ask you for an expected distinct count, and a bad guess hurts in one of two ways:
- If you guess too low, the filter is too small and its false positive rate rises.
- If you guess too high, you waste file space.
The read path
When a reader processes an equality predicate, it applies checks from cheapest to most expensive.
The footer is already in memory, so the statistics check costs nothing. The Bloom filter check needs one extra read of the filter bytes, which is usually far cheaper than reading the column chunk. When the filter answers "definitely not", the reader saves the whole column chunk read and decode.
What Bloom filters do and do not support
Bloom filters help with these predicates:
col == valuecol IN (v1, v2, ...), where the reader tests each value and skips the row group only if all of them miss
They do not help with:
- Range predicates such as
col > 10. A hash scatters neighbouring values, so there is no ordering to exploit. LIKEpatterns, inequality, orIS NULL.- Values that are present in most row groups. The filter always says "possibly", so you gain nothing.
Bloom filters pay off most for point lookups on high-cardinality, unsorted columns where the target value lives in only a few row groups.
Writing files with Bloom filters
Writer support differs by library, and some defaults are off. Check your writer's documentation before relying on any of these.
- parquet-mr and Spark use properties such as
parquet.bloom.filter.enabled, which can be set per column with a suffix like#user_id. A companion property sets the expected distinct count per column. - DuckDB and parquet-rs write Bloom filters under some conditions, with their own settings.
- PyArrow can read and write Parquet with the options used earlier in this tutorial. Its writer options for Bloom filters have been limited, so do not assume
pq.write_tableproduces them. Verify with a metadata tool.
Because a missing filter looks the same as no filter, always confirm that the file contains one. Inspect the column chunk metadata with a tool that reports the Bloom filter offset, such as parquet-cli or parquet-tools. Also confirm that your query engine uses it. Some engines read the filters only when a specific setting is on.
Failure modes and gotchas
- Filter never consulted. The file has filters but the reader ignores them. The query still works and is just slower, so measure bytes read.
- Wrong sizing. An underestimated distinct count raises the false positive rate. The filter still gives no false negatives, but it skips fewer row groups.
- Too many filtered columns. Each filtered column adds a filter to every row group. Enable them only on columns you filter by equality.
- Small files. If the file has one row group, the filter saves nothing, because you read that row group anyway.
- Rewriting and merging. Compacting files with a tool that does not preserve or recreate filters silently drops them.
- Type mismatches. The predicate value must hash the same way as the stored value. Comparing an
int32column against a value your engine treats asint64can disable the filter check in some engines.
Dictionary encoding offers a related skip trick. When every page of a column chunk is dictionary encoded, a reader can check the dictionary for the value. Bloom filters work even when pages fall back to plain encoding, and checking one is cheaper than loading a large dictionary.
Summary of the decision
Use min/max statistics for range filters and for columns whose values correlate with file order. Add Bloom filters for equality or IN lookups on high-cardinality columns that you cannot sort by. Size the filter from the distinct count per row group and the false positive rate you can tolerate. Then verify, with metadata inspection and measured bytes read, that your writer produces the filters and your reader uses them.
Exercise
A file has 50 row groups, each with 200,000 distinct order_id values in random order. You want a 1% false positive rate. Roughly how large is each row group's filter, and why do min/max statistics fail to skip row groups for order_id == 777?
Show answer
At 1%, the spec's figure is about 10.5 bits per distinct value, so 200,000 × 10.5 = 2,100,000 bits, which is about 262 KB per row group. Because the ids are in random order, every row group's min/max range spans nearly the whole id range, so 777 falls inside almost every interval and no row group can be skipped by statistics alone. The Bloom filter can rule out most of the row groups that do not contain 777.
Exercise
A query filters WHERE amount > 500 on a column that has a Bloom filter in every row group. Does the filter help? Explain.
Show answer
No. A Bloom filter only answers membership questions about exact values, because hashing destroys ordering. A range predicate like amount > 500 cannot be tested against it. Min/max statistics, or a page index, are the right tools for range predicates.