要避免读取数据,就需要一种廉价的方式来说“这里面没有”。尾部有两种:最小值/最大值统计,在某个值落在范围之外时排除整个行组;布隆过滤器,则能排除落在范围之内但从未存入的值。两者都不能证明某个值存在,只能证明它不存在。
用通俗的话说这个想法
我们在哪里。 主题 4 用最小值和最大值在范围过滤时跳过行组。这个主题直接读取这些统计信息,说明它们在何处失效(恰好落入某个范围内的单个值),并构建填补这一缺口的布隆过滤器。下一个主题讲文件过多的代价,而这一切都假定你已经避免了这个问题。
定义布隆过滤器
一个位数组,回答“这个值在集合里吗?”时,只会说“肯定不在”或“可能在”。每加入一个值,就置位由哈希选出的几个位;只有该值的所有位都已置位,才会报告它存在。它绝不会漏掉成员,但偶尔会把外人当成成员。
直接从尾部读取最小值和最大值
row_group_stats 从尾部为每个行组读出某列的最小值、最大值、空值个数和行数。对于按日期排序的文件中的日期列,范围很窄且几乎不重叠,所以查找某个日期只会落到一两个行组。但请注意“可能”这个词:落在某行组范围内的日期,不一定真的在这个行组里。
# The first three row groups of a file sorted by date: (min, max, nulls, rows)for stats in row_group_stats("by_date.parquet", "date")[:3]: print(stats)
(datetime.date(2000, 1, 3), datetime.date(2003, 3, 13), 0, 4000) (datetime.date(2003, 3, 13), datetime.date(2006, 5, 16), 0, 4000) (datetime.date(2006, 5, 16), datetime.date(2009, 7, 21), 0, 4000)
# A Saturday sits inside a group's range but is not in the file: statistics can only say "maybe"saturday = date(2020, 1, 4)print("row groups that might hold it:", groups_with_value("by_date.parquet", "date", saturday))print("rows really dated that day:", sum(1 for d in table["date"].to_pylist() if d == saturday))
row groups that might hold it: [6] rows really dated that day: 0
用布隆过滤器处理统计信息无法排除的情况
订单 ID 或成交 ID 在每个行组里都散布在整个范围内,因此最小值和最大值什么也排除不了。每个行组的布隆过滤器存下它所含 ID 的“指纹”。bloom_build 为每个值置位 k 个位,bloom_contains 检查这些位。位数组的大小决定了外人混进来的频率:每个值分到的位越多,误报越少,代价是尾部更大。
# 1,000 order IDs in a filter; then 1,000 IDs that were never added, at three filter sizesmembers = [f"order-{i}" for i in range(1000)]strangers = [f"other-{i}" for i in range(1000)]for nbits in (2_000, 10_000, 40_000): bits = bloom_build(members, nbits, 4) missed = sum(not bloom_contains(bits, nbits, 4, m) for m in members) false_positives = sum(bloom_contains(bits, nbits, 4, s) for s in strangers) print(f"{nbits:>6} bits: members missed {missed}, strangers let in {false_positives} of 1000")
2000 bits: members missed 0, strangers let in 546 of 1000 10000 bits: members missed 0, strangers let in 19 of 1000 40000 bits: members missed 0, strangers let in 0 of 1000
用在最小值和最大值失效的地方
像 date 这样已排序的列,靠统计信息就能很好地跳过,布隆过滤器只会增加体积。真正值得用的是未排序、基数高、按相等条件查找的列,比如订单 ID、成交 ID 或账号。它们只对 = 和 IN 查找有帮助,对范围条件没有帮助。
任务要求
- 1`row_group_stats` 与 `groups_with_value`按
path_in_schema找到列块,读取statistics.min、.max、.null_count。当min <= value <= max或没有统计信息时保留该行组。 - 2`bloom_build` 与 `bloom_contains`对每个值,在
bit_positions(value, nbits, k)的每个位置执行bits |= 1 << position;查询时,只要其中任何一位是 0 就返回False。
快速检查
向布隆过滤器查询某个 ID,它回答“否”。你能得出什么结论?
请选择一个答案。
实验:评分内容
4 个任务 · 100 分- 读取统计信息:
row_group_stats25 分 - 确定的“没有”或“可能有”:
groups_with_value25 分 - 构建布隆过滤器:
bloom_build25 分 - 查询过滤器:
bloom_contains25 分