Parquet 文件不是一整块长长的数字。它被切成行组,每个行组按列分成列块,每个列块再分成页,每一页先编码再压缩。理解这些层次,就能明白后续主题里每一种提速技巧,因为它们都是在其中某一层上跳过数据。
用通俗的话说这个想法
我们在哪里。 上一个主题说明列是分开存放的,尾部说明了位置。这一个再深入一层:行组是读取器可以单独取回的块,而编码决定了一列在下一个主题的压缩算法起作用之前需要多少字节。
定义行组
Parquet 文件的一个水平块:固定行数的数据,每列存成一个列块。每个行组有自己的元数据,读取器可以单独取回或跳过某个行组,而不碰其他行组。
行组:可以单独取回的块
写入端的 row_group_size 决定每个块放多少行。太小,文件会被每个行组的开销淹没;太大,读取器既无法细粒度跳过,也难以把一个块装进内存。write_grouped 选定大小,group_rows 从尾部读回结果,read_group 取回一个块而不读其他块。
# Cut the table into row groups of 10,000 rows and list them from the footerprint("row groups:", write_grouped(table, "g.parquet", 10000))print("rows in each:", group_rows("g.parquet"))
row groups: 4 rows in each: [10000, 10000, 10000, 3493]
# Fetch only the last row group, the tail of the last stock's barslast = read_group("g.parquet", 3)print(last.num_rows, "rows;", "first date:", last.column("date")[0], "| last date:", last.column("date")[-1])
3493 rows; first date: 2012-09-28 | last date: 2026-08-21
编码:压缩之前先减少字节
在列块内部,值首先被编码。PLAIN 原样写出每个值。字典编码(RLE_DICTIONARY)把每个不同的值只写一次,然后每行写一个小整数,相同整数的连续重复由 RLE 折叠。像 symbol 这样在 3.3 万行里只有五个不同值的列,几乎缩到没有。几乎每个值都不同的价格列甚至可能变大,如下面的输出所示。
# Dictionary encoding on and off: the encodings of symbol, and the bytes each setting gives symbol and closedef chunk_size(path, name): group = pq.ParquetFile(path).metadata.row_group(0) return sum(group.column(c).total_compressed_size for c in range(group.num_columns) if group.column(c).path_in_schema == name)for flag in (True, False): names = encodings_of(table, "d.parquet", "symbol", flag) print("dictionary", flag, names, "| symbol bytes:", chunk_size("d.parquet", "symbol"), "| close bytes:", chunk_size("d.parquet", "close"))
dictionary True ['PLAIN', 'RLE', 'RLE_DICTIONARY'] | symbol bytes: 161 | close bytes: 229798 dictionary False ['PLAIN', 'RLE'] | symbol bytes: 11167 | close bytes: 177572
有意识地选择行组大小
引擎默认每组约一百万行或约 128 MB,因为一个块既要大到压缩得好,又要小到能放进内存。对于按日期范围查询的文件,先按日期顺序写入行:这样每个行组只覆盖很窄的范围,后面的主题就能跳过其中大部分。
任务要求
- 1`write_grouped` 与 `group_rows`把
row_group_size传给pq.write_table,再读metadata.num_row_groups和每个row_group(g).num_rows。 - 2`read_group`
pq.ParquetFile(path).read_row_group(index)单独取回该块。 - 3`encodings_of`用
use_dictionary=...写出,按path_in_schema找到列块并返回sorted(chunk.encodings)。
快速检查
为什么字典编码对
symbol 列的压缩远大于对 close 列?请选择一个答案。
实验:评分内容
4 个任务 · 100 分- 选择行组大小:
write_grouped25 分 - 列出行组:
group_rows25 分 - 单独读取一个行组:
read_group25 分 - 查看列的编码:
encodings_of25 分