合并每小时追加所留下的小文件
阅读约需 35分钟 分钟,9节中含3个示例。
本章说明如何统计一张表所含的数据文件数量,如何在 Delta Lake、DuckLake 和 Iceberg 中将这些文件合并为数量更少的文件,以及每次合并后磁盘上留下了什么。问题出在数据加载上。第一章中的 pageviews 表在三种格式中都是每小时加载一次。每次加载就是一次提交,每次提交都会写出各自的数据文件。数据文件是保存表中若干行的 Parquet 文件。
每小时追加产生小文件
每次追加行的提交都会至少写入一个数据文件。一张表每小时加载一次,一天就会得到 24 个数据文件,每个文件存放一个小时的行,这里大约有 500 个。查询会打开其过滤条件无法跳过的每一个文件,而每次打开都要花费时间。表的元数据也会随着所列文件的增多而增长,因为每种格式都会为当前版本所用的每个数据文件保留一条记录。因此,即使总行数不大,小文件过多也会增加读取和规划的开销。
需要关注的是文件数量,因为它会随时间增长。文件大小同样重要,但本书不打印文件大小,因为以字节计的大小每次运行都会变化。统计文件数量也是检验压缩是否真正生效的可靠办法:压缩前后行数应当相同,而文件数应当下降。
解决办法是压缩。压缩会把许多小数据文件重写为数量更少、体积更大的文件。压缩与其他提交一样,也是一次提交:它写入替换文件,把这些文件列入元数据,并且只要表的历史仍然引用旧文件,就把旧文件留在磁盘上。第 7 章说明这些旧文件何时可以删除。
三种格式各有不同的调用方式。下表展示了每种格式对本章构建的六个每小时文件所做的处理。
| 格式 | 调用 | 压缩前文件数 | 压缩后文件数 |
|---|---|---|---|
| Delta Lake | optimize.compact() |
6 | 1 |
| DuckLake | ducklake_merge_adjacent_files |
6 | 1 |
| Iceberg | table.overwrite(table.scan().to_arrow_batch_reader()) |
6 | 1 |
表中的数量就是各个示例打印出的数量。每个示例都把截取数据中的六个小时按每小时一次加载写入一张没有分区的表,因此每种格式一开始都是每次加载对应一个数据文件。第 4 章中的分区表则会有不同的表现,因为在支持分区压缩的格式中,每个分区是各自单独压缩的。本章让表保持不分区,使文件数只有一个成因。
DuckLake 的数字还需要再多一项设置才有意义。这里每小时的加载大约有 500 行,高于第 1 章给出的内联行数上限,因此默认设置本来也会把它们写成文件。DuckLake 示例仍然在关闭内联的情况下挂载,这一设置已在该章中解释,目的是让文件数不取决于某次加载碰巧有多少行。
工作准则: 每次加载之后,统计每张表的数据文件数量,并根据文件到达的速率和读取方所需的文件大小来安排压缩。每小时加载一次,每张表每天会有 24 个文件,因此每天压缩一次是合理的初始选择。这是经验法则,而不是测量结果。只有当你自己的读取耗时或文件数量表明确有必要时,才提高压缩的频率。
使用 optimize.compact() 进行压缩
Delta Lake 是上表中三种格式的第一种。它的 Python 库 deltalake 把压缩放在表的 optimize 属性上。其 compact() 方法会把表中的小数据文件重写为较大的文件,并返回一个指标字典。字典中包含新增文件数和删除文件数,以及本书不打印的大小字段。
你把这六个小时的数据装入一张 Delta 表,每小时一次追加,然后统计表所列出的文件数,执行压缩,再统计一次。每次统计都取自该表对其当前版本所列出的文件清单。
1"""Load six hourly appends into a Delta Lake table, compact it, and count its files and rows before and after.2The point rests on the file-count lines, and on the row count read from the version before the compaction."""34from deltalake import DeltaTable, write_deltalake56from lib.lakehouse import delta_file_count, new_warehouse, read_cut_hour, read_delta789def main():10 with new_warehouse() as wh:11 path = str(wh.root / "delta" / "pageviews_hourly")12 for hour in range(6):13 write_deltalake(path, read_cut_hour(hour), mode="append")1415 table = DeltaTable(path)16 version_before = table.version() # the version the read at the end goes back to17 print(f"files before compaction: {delta_file_count(table)}") # counts the files this version lists, not the disk1819 metrics = table.optimize.compact() # a dict; numFilesAdded and numFilesRemoved are the two counts printed below20 print(f"files added by compaction: {metrics['numFilesAdded']}")21 print(f"files removed by compaction: {metrics['numFilesRemoved']}")2223 table = DeltaTable(path)24 print(f"files after compaction: {delta_file_count(table)}")25 print(f"rows after compaction: {len(read_delta(path))}")26 before = read_delta(path, version=version_before)27 print(f"rows at the version before compaction: {len(before)}")28 parquet = list((wh.root / "delta").rglob("*.parquet")) # every file on disk, including ones the current version dropped29 print(f"parquet files on disk after compaction: {len(parquet)}")303132if __name__ == "__main__":33 main()
python file-counts-before-after.pyfiles before compaction: 6
files added by compaction: 1
files removed by compaction: 6
files after compaction: 1
rows after compaction: 2999
rows at the version before compaction: 2999
parquet files on disk after compaction: 7
压缩改变的是文件,而不是行。调用前,表列出 6 个数据文件,调用后列出 1 个;读取当前版本返回 2999 行,与之前的行相同,只是分布在更少的文件中。
调用所返回的指标从库的角度统计了同一变化:新增 1 个文件,删除 6 个文件。
压缩并没有删除旧文件。按调用之前的版本读取,表仍然返回全部 2999 行,因为该版本指向的是旧文件。调用之后,目录中有 7 个 Parquet 文件,即六个旧文件和一个新文件。Delta Lake 通过一个单独的步骤 vacuum 来删除任何保留版本都不再使用的文件,第 7 章会演示这一步。在该步骤运行之前,压缩只会增加磁盘上的文件,而不会减少任何文件。
这里的 Delta 读取通过库的查询构建器进行,本书中所有 Delta 读取都是如此。由于关注点在于文件数,行只按数量进行比较。
**工作准则:**按第一节给出的周期压缩 Delta 表(按小时加载的数据每天压缩一次),并在事后检查文件数。在删除任何文件之前,先阅读第 7 章中的保留规则:压缩会新增一次提交,并保留旧文件,因此在 vacuum 运行之前,它会增加存储占用。
DuckLake 中的合并
DuckLake 提供合并(compaction)作为一项维护函数,你可以通过 SQL 调用它。这个函数只需调用一次,并会为它所合并的每张表返回一行,说明它做了什么。下一部分将介绍这个函数,以及它会跳过的那一种情况。
合并相邻文件
ducklake_merge_adjacent_files 接受一个目录,以及可选的表名和模式名;当表不在 main 模式中时,调用必须给出模式名。不给表名时,它会合并所有表的文件。DuckLake 文档称,该函数可以“将多个 Parquet 文件合并为一个 Parquet 文件,其中包含由多个快照插入的数据”(DuckLake 文档:合并文件)。合并不需要先让快照过期,也不会立即删除旧文件。这两点对本章其余部分都很重要。由于合并不会让快照过期,每个较早的快照仍然引用旧文件。
对于合并之前的快照,合并会留下什么?下面的示例读取了这样一个快照。它在关闭内联的情况下附加目录,为六个小时各执行一次插入,然后调用一次合并。该表位于 wiki 模式中,所以调用中要指明它。示例先读取合并之前的快照编号,以便之后读取表在那一时刻的状态。
1"""Merge six DuckLake data files, then read a snapshot from before the merge to see what the merge left behind.2The point rests on the data-file lines, and on the row count read at the earlier snapshot."""34from lib.lakehouse import (5 DUCKLAKE_ALIAS,6 NAMESPACE,7 TABLE,8 connect_ducklake,9 create_ducklake_table,10 ducklake_file_count,11 new_warehouse,12 read_cut_hour,13)141516def main():17 with new_warehouse() as wh:18 lake = connect_ducklake(wh.con)19 create_ducklake_table(lake, wh.root) # inlining is off here, so every insert writes a data file20 table = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"21 for hour in range(6):22 lake.register("hour", read_cut_hour(hour))23 lake.execute(f"INSERT INTO {table} SELECT * FROM hour")24 lake.unregister("hour")25 # the newest snapshot before the merge, which the read at the end goes back to26 before = lake.execute(f"SELECT max(snapshot_id) FROM ducklake_snapshots('{DUCKLAKE_ALIAS}')").fetchall()[0][0]27 print(f"data files before merge: {ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE)}")2829 # the schema is named because the table is not in main; the call returns one row30 result = lake.execute(31 f"CALL ducklake_merge_adjacent_files('{DUCKLAKE_ALIAS}', '{TABLE}', schema => '{NAMESPACE}')"32 ).fetchall()33 # the row's fields: schema, table, files merged, files created34 print(f"files merged: {result[0][2]}")35 print(f"files created: {result[0][3]}")36 print(f"data files after merge: {ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE)}")37 print(f"rows after merge: {lake.execute(f'SELECT count(*) FROM {table}').fetchall()[0][0]}")38 old = lake.execute(f"SELECT count(*) FROM {table} AT (VERSION => {before})").fetchall()[0][0]39 print(f"rows at the snapshot before merge: {old}")40 # every Parquet file under the data path, including the ones the table no longer lists41 parquet = list((wh.root / f"{DUCKLAKE_ALIAS}_data").rglob("*.parquet"))42 print(f"parquet files on disk after merge: {len(parquet)}")434445if __name__ == "__main__":46 main()
python compact-ducklake.pydata files before merge: 6
files merged: 6
files created: 1
data files after merge: 1
rows after merge: 2999
rows at the snapshot before merge: 2999
parquet files on disk after merge: 7
合并的结果行说明了它做了什么:6 个文件被合并为 1 个文件。此后表中列出 1 个数据文件,而合并之前是 6 个。结果行还给出了模式名和表名,因此合并若指向了错误的表,在读取其他内容之前就能看出来。
旧快照仍然可以读取。在合并之前的快照上计数,返回 2999 行,与当前表返回的计数相同。磁盘上的 Parquet 文件有 7 个,即六次插入写出的六个文件,加上合并写出的那一个。这六个旧文件会一直留在磁盘上,直到第 7 章中的清理将它们删除。
合并会跳过附带删除文件的文件。删除文件是对已删除行的记录;删除行时,DuckLake 写入删除文件,而不是重写数据文件。第 5 章会在 DuckLake 中写出删除文件,所以这一限制在那里适用。DuckLake 文档指出,重写这些文件的调用是 ducklake_rewrite_data_files,其默认的 delete_threshold 为 0.95,即只有当文件中被删除的行占到这一比例时才会重写该文件(DuckLake 文档:重写带删除的文件)。这个默认值应当按你自己的数据来选择,而不是不加检查地接受。
工作准则: 在某一时段的插入全部完成之后运行 ducklake_merge_adjacent_files,并读取它返回的文件数。合并不会移除已删除的行,因此对于带有删除文件的表,应调用 ducklake_rewrite_data_files,并使用你为该表选定的 delete_threshold,然后检查结果。
重写表以实现压缩
在 pyiceberg 的固定版本下,Iceberg 中的压缩是通过覆盖写入来重写表。本章重写整张表,这适用于未分区的表。你先用扫描读取表,再用扫描返回的行覆盖写入该表。覆盖写入会把这些行写成替换的数据文件,旧文件则从当前快照中移除。这是本书中 Iceberg 唯一的压缩路径,它是为弥补一个缺失的调用而采用的变通办法,下一部分会对此作出说明。
评判一次重写,要看它留下了什么。下面的检查读取经过六次追加和一次覆盖写入之后表的文件和行,并读取重写之前的一个快照。
1"""Rewrite an unpartitioned Iceberg table by overwriting it with its own scan, then check its data files, its snapshot2history and a snapshot from before the rewrite. The point rests on the data-file lines and on the row count of snapshot 6."""34from lib.lakehouse import (5 create_iceberg_table,6 iceberg_file_count,7 new_warehouse,8 read_cut_hour,9 scan_arrow,10 snapshot_labels,11)121314def main():15 with new_warehouse() as wh:16 table = create_iceberg_table(wh)17 for hour in range(6):18 table.append(read_cut_hour(hour))19 last_append = table.current_snapshot().snapshot_id # the snapshot after the sixth append20 print(f"data files before rewrite: {iceberg_file_count(table)}")2122 # a batch reader, so the rows are not all read into one Arrow table first23 table.overwrite(table.scan().to_arrow_batch_reader())24 print(f"data files after rewrite: {iceberg_file_count(table)}")25 print(f"rows after rewrite: {len(scan_arrow(table))}")2627 # sorted by sequence number, which puts the snapshots in commit order28 snapshots = sorted(table.snapshots(), key=lambda snapshot: snapshot.sequence_number)29 # labels count up in commit order, so the sixth append is snapshot 630 labels = snapshot_labels([snapshot.snapshot_id for snapshot in snapshots])31 operations = [snapshot.summary.operation.value for snapshot in snapshots]32 print("snapshot operations in order: " + ", ".join(operations))33 print(f"{labels[last_append]} rows: {len(scan_arrow(table, snapshot_id=last_append))}")34 # every Parquet file in the warehouse, including those that only older snapshots still hold35 parquet = list((wh.root / "warehouse").rglob("*.parquet"))36 print(f"parquet files on disk after rewrite: {len(parquet)}")373839if __name__ == "__main__":40 main()
python iceberg-rewrite-by-overwrite.pydata files before rewrite: 6
data files after rewrite: 1
rows after rewrite: 2999
snapshot operations in order: append, append, append, append, append, append, delete, append
snapshot 6 rows: 2999
parquet files on disk after rewrite: 7
数据文件从 6 个降到 1 个,表的读取者看到的仍是相同的 2999 行,读取方式不变,只是来自更少的文件。这次重写是一次提交,新增两个快照。按提交顺序,这些操作是六次追加,然后是 delete 和 append:delete 快照从表中移除所有数据文件,append 快照则加入重写后的文件。当前快照只移动一次,因此没有读取者会看到空表,但历史中保留了这两个快照。以这种方式删除整个文件,就是第 5 章所描述的 Iceberg 删除所采用的写时复制行为。
重写之前的快照仍能读出每一行。标签按提交顺序递增地给快照编号,因此快照 6 是重写之前的最后一次追加。在该快照下读取,表仍返回 2999 行。磁盘上的 Parquet 文件共 7 个:六个旧文件,加上这次重写写入的一个文件。第 7 章介绍如何使旧快照过期,并统计它们仍占用的内容。
工作准则: 仅当重写期间没有其他写入者向该表提交时,才通过覆盖写入来重写 Iceberg 表。对于未分区的表,应像本示例那样以流式方式读取扫描结果。对于分区表,扫描必须用 to_arrow() 读取,因此整个扫描结果必须能放进作业的内存。流式读取器只能读取一次:如果提交失败,请为下一次尝试构建新的读取器。每次重写之后都要检查文件数和行数,并在确认结果之前保留重写之前的快照。
这部分尚未翻译,因此以英文显示。
Why pyiceberg has no rewrite call
The pyiceberg API documentation lists overwrite among its table operations (PyIceberg API documentation). Its one sentence on compaction is in the note on fast appends, and it is about metadata: the page says that metadata compaction is planned. It says nothing about data files. Its only maintenance call is expire_snapshots, which chapter 7 covers. The source of pyiceberg 0.12.0, in pyiceberg/table/__init__.py, has no method that compacts or rewrites data files. Its write operations are append, overwrite, delete, upsert, dynamic_partition_overwrite and add_files. Every one except add_files writes data files, and add_files registers files that already exist and writes none. dynamic_partition_overwrite, and overwrite with an overwrite_filter, can replace the rows of one partition, so a partitioned table can be rewritten one partition at a time. A compaction is therefore a rewrite built from those operations.
The rewrite has a memory cost that the file counts do not show, and the way the scan is read decides it. table.scan().to_arrow() reads the whole current snapshot into one Arrow table in memory before the overwrite starts. The rewrite above passes table.scan().to_arrow_batch_reader() instead, and pyiceberg documents that a streamed overwrite is microbatched by write.target-file-size-bytes, so its memory stays bounded. Streaming works only on unpartitioned tables, which this chapter uses. A partitioned table has to be read with to_arrow(), so memory must hold all of its rows at once. The bound is pyiceberg's documented behaviour, not a measurement made here.
The rewrite also reads every file and writes every file, including the ones that were already large enough. A table whose files are mostly the right size gets no benefit from it. This is the reason to use it only when the file count has grown and the table fits in memory.
Working rule: Check the pyiceberg release notes at each upgrade for a compaction call, because a call would replace the overwrite rewrite in this chapter. Until then, treat the overwrite as a batch job, run it when no other writer is committing, and for a partitioned table budget memory for the whole scan.
在信任每次压缩之前先检查
本章的示例合起来会打印四项内容,这四项也正是在执行任何压缩之后都应当检查的内容。第一项是表自身文件列表中的文件数。第二项是当前版本的行数,它必须与压缩前的行数一致。第三项是压缩之前的某个版本或快照的行数,它必须仍然可以读取。第四项是表所在位置下的 Parquet 文件数,它应当等于文件数加上等待清理的旧文件数。
前两项检查表明压缩确实完成了它声称的工作,并且没有改变任何行。第三项检查表明历史记录仍然可用,这对任何固定在旧版本上的读取方都很重要。第四项检查表明压缩在磁盘上留下了什么。第一项与第四项来自不同的来源,本书的示例把两者都打印出来,这样不一致之处会直接显示在输出中,而不会被藏在某一个数字里。第四项的计数在 DuckLake 表中是 7,在 Iceberg 表中是 7,两者都比仍在列表中的文件多一个。通过前三项检查的压缩,不应为这样的计数负责。多出的文件属于第 7 章要清理的状态。
每个库都有各自的文件列表。Delta 示例统计当前版本的 URI,DuckLake 示例向其目录查询表的文件,Iceberg 示例统计表文件检查结果中的条目数。这三个数字都是从元数据中读取的,因此不依赖目录列表,而目录列表是第二个来源。当两者不一致时,请先停下来查明原因,再执行下一次压缩。
检查失败时,请停止作业,并保持表的现状。不要再运行第二次压缩来修复第一次压缩,因为每次运行都是一次提交,第二次运行会使历史记录更难阅读。请按顺序读取表的历史中的各次提交,找到改变行数的那一次,再据此作出决定。表仍保持原样时,故障发生之前的状态更容易检查。
工作准则: 每次压缩之后,都要把行数与压缩前的行数进行比较,并读取压缩之前的某个版本。改变了行数的压缩是一个故障,必须先修复,才能在该表上运行其他任何操作。
生产环境中会出什么问题
存储先增长,后缩小。 本章中的每一次压缩都会写入替换文件,并把旧文件留在磁盘上。计数说明了这一点。DuckLake 合并之后,表中列出 1 个数据文件,而磁盘上仍有 7 个 Parquet 文件;Iceberg 重写之后,表中列出 1 个,磁盘上仍有 7 个。如果压缩运行时没有配套的过期步骤,存储开销反而会比压缩之前更高。应当把过期与清理和压缩一并规划,并在两者都完成之后测量磁盘。其征兆是:每次运行之后磁盘都在增长,而表的行数和文件数保持不变。
已删除的行会一直保留,直到某次重写处理它们。 DuckLake 合并会跳过任何带有删除文件的数据文件,如合并一节所示。含有删除、却只做合并的表,会让这些文件保持原样。对这些文件应使用 ducklake_rewrite_data_files,并自行选定阈值。请在前后分别测量行数,因为仅靠合并并不能让你看到已删除的行仍留在文件中。需要留意的是:带有删除文件的数据文件个数在每次合并之后都保持不变。
并发写入者在此未经测试。 本章的示例每次只运行一个写入者,没有测试与提交相重叠的压缩。请在你自己的引擎上测试这种重叠;在完成该测试之前,应把压缩安排在没有写入者提交的时间窗口内。三者之中,Iceberg 重写最容易受到影响,因为它要读取整张表,再把整张表写回。重叠失败时,写入者或压缩会报出错误,而本书并未复现过这样的错误。
太频繁耗费提交,太稀疏耗费读取。 每次压缩都是一次提交,每次提交都会增加元数据。每次加载之后都压缩,会使每次加载对应的提交数翻倍;每月只压缩一次,则会让小文件累积一个月。前者表现为提交数的增长快于加载次数,后者表现为查询时间随文件数而上升。这是需要你在自己的表上测量的权衡,而不是示例所能证明的规则。
文件个数的目标不是文件大小的目标。 单个特别大的文件,会使读取者可并行的工作变少,也使可按文件级统计信息裁剪的文件变少。这些示例以文件个数为目标,并不输出文件大小。这是一项关于读取者的判断,目标应由你的读取者的查询时间来确定。如果一次压缩产出了单个特别大的文件,而查询时间随后变差,这就是警告信号。
工作准则: 把压缩安排在过期与清理的旁边,不要与它们分开。每次运行之后,执行检查一节中的四项检查;如果行数发生变化,或者并发写入者失败,就停止这一调度。
本章做出的决定
- 每种格式都使用其自身库的调用,本章没有任何示例使用 DuckDB 的 Iceberg 或 Delta Lake 扩展。读写都通过 Python 库和 DuckDB 的 DuckLake 支持完成,因此每个计数都来自写入这些文件的工具。
- DuckLake 示例在关闭数据内联的情况下附加。关闭内联后,无论加载规模多大,每个计数都是文件的数量。
- 文件计数来自各个库自己的文件列表。磁盘上的 Parquet 计数是第二重核对,且不输出任何文件大小。
- 这些表没有分区,因此每个计数只有一个成因:加载的次数。分区的情形留给讲分区演进的章。
- Iceberg 的合并是通过覆盖写入完成的重写,因为 pyiceberg 0.12.0 没有合并调用。该重写以流式方式处理扫描,pyiceberg 允许对未分区的表这样做。本章指出了这一变通办法,以及分区表仍然存在的内存开销。
- 本章不会让任何快照过期,也不会删除任何文件。第 7 章两者都会做,而本章的计数正是那项工作的起点。
- 工作准则中的调度安排只是一个起点。本书不声称存在最佳间隔,因为合适的间隔取决于表的文件到达得有多快,以及读取方需要这些文件有多大。
本章,在本版次中
版次 2026.11.10示例于 2026年11月20日 通过本章 3个示例 个示例中有 3 个通过
译自英文版图书,版次 2026.11.10。