在不重写旧文件的情况下更改分区

阅读约需 38分钟 分钟,7节中含4个示例。

版次 2026.11.10 示例于 2026年11月20日 通过 39个示例中有39个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.10。 阅读原文

本章在 Iceberg、Delta Lake 和 DuckLake 中更改一张表的分区方式,并统计更改前后一次查询计划读取的文件数。分区决定查询要打开哪些文件,因此分区的变化会改变每个读取方所付出的代价。至于这一变化对已写入的文件有何影响,则取决于表格式。

wiki.pageviews_hourly 的看板每次只读取一个小时的数据,该表按天分区。现在的问题是,如何在不重写已加载数据的前提下,把它改为按小时分组。开头的三次按小时加载已经落盘。因此,团队希望从 02 点之后的每一次加载起都采用小时分区,同时需要弄清这一更改对现有的三次加载有什么影响,并且不复制它们。

这一更改有两项成本。第一项是实施更改所需的工作量,这取决于表格式是否保持旧文件不动。第二项是之后每次查询所付出的代价,因为跨越更改点的查询,会同时规划出两个时期的文件。本章用各个库给出的计数来衡量这两项成本,使决策建立在表的实际行为之上,而不是建立在对表格式的描述之上。

分区规范同样有版本

最近一次修改见于版次 2026.11.7

分区规范说明表如何对行进行分组,例如按 hour_utc 的每一天分为一组。在 Iceberg 中,规范是表元数据的一部分,而列出每个数据文件的清单(manifest)会记录该文件写入时所用的规范。更改规范会生成带有自己 ID 的第二个规范。之后的写入使用第二个规范,磁盘上已有的文件则保留其写入时的规范。Iceberg specification 指出,更改后的规范会以唯一的规范 ID 添加到表的分区规范列表中,并且每个清单都会记录写入它时所用规范的 ID(partition_spec_id)。

这样,表中就并存着两个分区时期。查询会读取它所打开的每个文件的规范,因此一次扫描可以覆盖多个规范下的文件。这一切由规划器代为完成,所以更改的代价体现在执行计划和文件数量上,而不是查询返回的行上。针对 hour_utc 编写的查询在规范更改后文本保持不变,这正是该设计的意义所在。不同的是规划器所打开的文件集合。本章其余部分将展示这两方面。

规范的更改只涉及元数据。Iceberg 写入一个带有自己 ID 的规范,而不动数据文件,下一节中的文件数量会说明这一点。

旧规范也会作为历史保留下来。表会记录它曾有过的每一个规范,因此读取者始终可以查明某个文件是按哪些字段写入的。对于多次更改分区的团队,这一点很重要:每个文件都以自己的规范回答“我是如何被切分的”这一问题,无需任何人记住更改的先后顺序。这份记录属于元数据,开销很小,但表的规范列表会随每次更改而增长。

另外两种格式处理分区的方式不同,这些差异决定了更改的代价。Delta Lake 按名称获取分区列,因此写入方会将它们创建为列。DuckLake 则把分区键保存在它的目录(catalog)中。两者各有说明,见关于其他格式的一节,该节位于本章其余部分所依赖的 Iceberg 步骤之后。

工作准则: 当读取者的过滤条件发生变化,且当前规范为这些条件规划的文件过多时,才更改 Iceberg 分区规范。如果当前规范为这些过滤条件规划的文件已经很少,就不要改动。更改时,让旧文件留在原处。在表的运行手册中记录这次更改,包括日期、旧字段与替换字段,以及促成更改的读取者过滤条件。同时保留更改前后的规划计数,如关于查询扫描内容的一节所示。

从按天分区迁移到按小时分区

最近一次修改见于版次 2026.11.10

每个示例都再次从切片构建自己的表,使用的是原始列,而不是第 3 章新增的那些列。要把表改为按小时分区,只需把 hour_utc 上的一个转换换成另一个。Iceberg 按某一列的转换结果分区:天转换把每一行放到它所属的日历日之下,小时转换则把每一行放到它所属的小时之下。pyiceberg 库借助 pyiceberg-core 包来计算这些转换,而天转换在写入时会导入该包。因此,只安装了 pyiceberg 的环境,在按天或按小时分区的表上执行第一次追加时就会失败(pyiceberg 0.12.0 源码,pyiceberg/transforms.py,DayTransform.pyarrow_transform)。本书固定的版本中包含 pyiceberg-core 0.11.0,与 pyiceberg 0.12.0 并列。

表一开始使用按天的分区规格。00 时至 02 时的数据在该规格下加载。随后分区规格发生变更,03 时至 05 时的数据在按小时的规格下加载。这次变更是一个 update_spec() 代码块,它删除天字段并添加小时字段:

with table.update_spec() as update:
    update.remove_field("ts_day")
    update.add_field("hour_utc", HourTransform(), "ts_hour")

两个调用放在同一个代码块中,因此表只发生一次规格变更,且天字段已不复存在。按顺序打印出的规格列表给出了每个字段的转换,由此可以看出这次变更做了什么。字段名沿用本书的约定,即 ts_day 和 ts_hour,所以规格标签就能说明每个字段应用的是哪种转换。源列仍然是 hour_utc。天字段和小时字段是对该列的两种转换,因此读取方针对该列的过滤条件在两个时期内都继续有效。

day-then-hour-spec.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Partition an Iceberg table by day, change its spec to hour, and load more hours under the new spec.The two `data files` lines carry the point, one count for each spec."""from collections import Counterfrom pyiceberg.partitioning import PartitionField, PartitionSpecfrom pyiceberg.transforms import DayTransform, HourTransformfrom lib.lakehouse import create_iceberg_table, new_warehouse, read_cut_hour, safe_error, scan_arrowdef main():    try:        with new_warehouse() as wh:            # source_id 1 is hour_utc, the table's first column: the day transform reads that column            day_spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="ts_day"))            table = create_iceberg_table(wh, partition_spec=day_spec)            for hour in range(3):  # hours 00 to 02, written under the day spec                table.append(read_cut_hour(hour))            # hour_utc is the source of the hour field too, as it was of the day field            with table.update_spec() as update:                update.remove_field("ts_day")                update.add_field("hour_utc", HourTransform(), "ts_hour")            for hour in range(3, 6):  # hours 03 to 05, written under the hour spec                table.append(read_cut_hour(hour))            # the labels number the specs in the order they were made, so the output names no spec ID            specs = sorted(table.specs())            labels = {spec_id: f"spec {number}" for number, spec_id in enumerate(specs, start=1)}            for spec_id in specs:                for field in table.specs()[spec_id].fields:                    print(f"{labels[spec_id]} field {field.name}: transform {field.transform}")            # group the data files by the spec_id each one carries            files = Counter(table.inspect.data_files().column("spec_id").to_pylist())            for spec_id in specs:                print(f"{labels[spec_id]} data files: {files[spec_id]}")            print(f"rows in table: {scan_arrow(table).num_rows}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
输出python day-then-hour-spec.py
spec 1 field ts_day: transform day
spec 2 field ts_hour: transform hour
spec 1 data files: 3
spec 2 data files: 3
rows in table: 2999

从输出的顶部开始读。规格 1 只有一个字段 ts_day,使用天转换。规格 2 只有一个字段 ts_hour,使用小时转换。变更之后,表中的行全部都在:2999 行,即变更前的三个小时与变更后的三个小时。

规格变更是唯一只触及元数据的步骤。它前后的两次加载照常写入数据文件,下一小节会说明每个文件属于哪一个规格。

这里的错误不会在变更本身中暴露,而是在之后才显现。如果规格列表有误,变更之后的每次加载都会按错误的分区方式写文件,而下一节的计数是你最先看到问题的地方。变更之后立即检查规格列表,只多一行输出,却能省去一次重写。

工作准则: 在 Iceberg 中,把规格变更放在一个 update_spec() 代码块里完成,使旧字段在添加替代字段的同一次变更中被删除。只有当两次编辑之间必须运行某个步骤时,才把它们拆开;本章没有这样的步骤。变更之后要检查规格列表,并在第二个规格下加载任何数据之前,确认字段名和转换正是你想要的。

各规格下写入的文件

最近一次修改见于版次 2026.11.8

每个数据文件都属于写入它时所用的规格,因此按规格统计文件数量,就能知道每个文件来自哪个时期。数据文件的清单记录了每个文件的规格 ID,所以统计时可以按规格对文件分组,每个规格得到一个计数,标签分别为“spec 1”和“spec 2”。这些标签按规格创建的先后顺序编号,因此输出中不会出现任何规格 ID。

三次按天分区的加载在规格变更之后保留了它们的文件。输出显示,规格 1 下有 3 个数据文件,规格 2 下有 3 个,所以三次按小时分区的加载写入了它们自己的文件,而规格变更本身没有写入任何文件。如果变更之后规格 1 下的计数减少了,就说明有操作重写了这些文件,在你信任旧时期的数据之前,需要先查明是什么操作所致。

工作准则: 每次规格变更之后,统计各规格下的数据文件数量,并将计数与你执行过的加载进行比对。如果在没有计划重写的情况下计数发生了变化,就说明这次变更的影响超出了你的预期,应先停下来检查,再进行下一次加载。

检查查询扫描了什么

最近一次修改见于版次 2026.11.10

分区规格是一种跳过文件的方式。查询读取文件之前,规划器会查看文件的分区值和列边界,并丢弃不可能满足过滤条件的文件。查询的开销取决于它纳入规划的文件有多少。因此,检验一次变更的办法,是统计典型过滤条件在变更前后各规划了多少个文件,而不是比较行数。规划一次扫描只返回文件列表,并不读取其中的行,所以这个计数足够廉价,可以在每次变更之前运行。

剪枝是这次变更产生收益之处,所以要把三次扫描各规划两遍:一遍在按天分区的规格下(参见迁移到按小时分区),另一遍在三次按小时分区的加载之后。其中两个过滤条件各自只要求一个小时:01 时(在变更之前加载)和 04 时(在变更之后加载)。第三个没有过滤条件,是一次全表扫描。

plan-files-by-partition.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Count the files an Iceberg scan plans for one hour, for another hour and for the whole table, before and after a spec change.The filtered counts are the lines to compare, one pair for each filter."""from pyiceberg.partitioning import PartitionField, PartitionSpecfrom pyiceberg.transforms import DayTransform, HourTransformfrom lib.lakehouse import create_iceberg_table, hour_filter, new_warehouse, read_cut_hour, safe_errordef plan_counts(table):    """Return the files planned for hour 01, for hour 04 and for no filter, in that order."""    # plan_files gives the planned files as a list; each printed count is that list's length    one_hour = len(table.scan(row_filter=hour_filter(1)).plan_files())    # hour 04 is loaded only after the change, so the filter can match only an hour-partitioned file    hour_four = len(table.scan(row_filter=hour_filter(4)).plan_files())    everything = len(table.scan().plan_files())    return one_hour, hour_four, everythingdef main():    try:        with new_warehouse() as wh:            day_spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="ts_day"))            table = create_iceberg_table(wh, partition_spec=day_spec)            for hour in range(3):  # hours 00 to 02, under the day spec                table.append(read_cut_hour(hour))            one_hour, hour_four, everything = plan_counts(table)            print(f"before the change, one-hour filter plans: {one_hour}")            print(f"before the change, hour 04 filter plans: {hour_four}")            print(f"before the change, no filter plans: {everything}")            with table.update_spec() as update:                update.remove_field("ts_day")                update.add_field("hour_utc", HourTransform(), "ts_hour")            for hour in range(3, 6):  # hours 03 to 05, under the hour spec                table.append(read_cut_hour(hour))            one_hour, hour_four, everything = plan_counts(table)            print(f"after the change, one-hour filter plans: {one_hour}")            print(f"after the change, hour 04 filter plans: {hour_four}")            print(f"after the change, no filter plans: {everything}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
输出python plan-files-by-partition.py
before the change, one-hour filter plans: 1
before the change, hour 04 filter plans: 0
before the change, no filter plans: 3
after the change, one-hour filter plans: 1
after the change, hour 04 filter plans: 1
after the change, no filter plans: 6
阶段 单小时过滤 04 时过滤 无过滤
变更之前,三次按天分区的加载 1 0 3
变更之后,新增三次按小时分区的加载 1 1 6

无论某个小时是在哪个时期加载的,每个过滤条件都能找到它自己那个小时所在的文件。单小时过滤在变更之前规划了 1 个文件,在变更之后规划了 1 个文件;04 时过滤在变更之前规划了 0 个文件,在变更之后规划了 1 个文件。01 时是在变更之前加载的,所以两次规划中的那一个文件,都是该小时对应的按天分区的文件。变更之前,三个文件同属一天,规划器只能依据它们的 hour_utc 边界跳过另外两个。变更之后,三个按小时分区的文件同样会被跳过。04 时的情形正好相反。没有任何按天分区的文件包含它,所以它唯一匹配的是包含该小时的那个按小时分区的文件。这些计数并不能说明规划器是依据分区值还是依据列边界跳过了某个文件,它们只显示规划保留了什么。

规划计数统计的是文件数,而不是字节数。由于文件大小不一,两次计数相同的规划,读取的数据量可能不同。尽管如此,计数仍然是正确的第一项检查,因为规划器正是依据这个数字做出决定的。当计数一致而查询仍然很慢时,应转而查看文件大小和查询本身。

全表扫描要为表写入过的每一个文件付出代价。它的规划从 3 个文件增长到 6 个,即按天分区的文件加上按小时分区的文件。这种增长是把旧文件留在原处所付出的代价,也是除了带过滤条件的扫描之外还要统计全表扫描的原因。

工作准则: 每次变更分区之前和之后,都要规划读者使用的过滤条件以及全表扫描,并把这些计数与运行手册条目一起保存。如果原本只规划一个文件的过滤条件开始规划许多文件,就说明这次变更破坏了该过滤条件的剪枝,应当在该规格下进行下一次加载之前,修改规格或者过滤条件。

这部分尚未翻译,因此以英文显示。

Partitioning in the other formats

最近一次修改见于版次 2026.11.10

In the other two formats the same change costs something different, though the rows read back are the same in all three. The files and the plan are what change. The table below sums up the three.

Format How the change is made Files already written What to check after
Iceberg One update_spec() block Kept, and still under their old spec File count per spec; plan counts
Delta Lake Full overwrite with schema_mode="overwrite" Written again in a later version; old version kept Row count; file count; partition columns of the old version
DuckLake ALTER TABLE ... SET PARTITIONED BY Kept; the setting applies to later loads File count after one load; the partition key

Delta Lake partitions by plain columns, and its partition option takes column names, not expressions. The Delta Lake protocol defines partitionColumns as an array containing the names of columns by which the data is partitioned. A generated column can compute day or hour inside the table, but it raises the table's writer protocol, so this book computes both in the writer. A helper, with_partition_columns, adds the two string columns from hour_utc before each write. The table starts partitioned by day, and a change to hour is refused unless the write is a full overwrite that also replaces the schema:

DeltaError: Generic error: Specified table partitioning does not match table partitioning: expected: ["day"], got: ["hour"]. To change partition columns, use full table overwrite with schema overwrite and no replaceWhere predicate.

Try the change with a plain mode="overwrite" first, and the library refuses it with that error. The same write with schema_mode="overwrite" then goes through. That is the setting the library's API at the pins uses in place of the older overwrite_schema flag. The rows are read into memory before the overwrite starts, because an overwrite replaces every row the table holds. Writing the rows back is the only way to keep them.

delta-partition-overwrite.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Change a Delta Lake table's partition columns from day to hour, which rewrites the table.Read the error line from the plain overwrite first, then the version and row lines after the rewrite."""import pyarrow.compute as pcfrom deltalake import DeltaTable, write_deltalakefrom lib.lakehouse import delta_file_count, new_warehouse, read_cut_hour, read_delta, safe_errordef with_partition_columns(rows):    """Add the day and hour columns that Delta partitions by. Delta partitions only by plain columns."""    rows = rows.append_column("day", pc.strftime(rows["hour_utc"], format="%Y-%m-%d"))    # %H is the 24-hour clock, zero-padded, so hour 04 is the string "04"    return rows.append_column("hour", pc.strftime(rows["hour_utc"], format="%H"))def main():    try:        with new_warehouse() as wh:            path = f"{wh.root}/delta/pageviews_hourly"            for hour in range(3):                write_deltalake(path, with_partition_columns(read_cut_hour(hour)), partition_by=["day"], mode="append")            table = DeltaTable(path)            print(f"partition columns before: {table.metadata().partition_columns}")            print(f"version before: {table.version()}")            print(f"data files before: {delta_file_count(table)}")            # read first, so the rows are in memory before the overwrite below writes them back            rows = read_delta(path)            try:                # no schema_mode here, so the library refuses the change and the error is printed                write_deltalake(path, rows, partition_by=["hour"], mode="overwrite")            except Exception as exc:                print(f"change without schema mode: {safe_error(exc, wh)}")            # schema_mode is what lets the partition columns change in a full overwrite            write_deltalake(path, rows, partition_by=["hour"], mode="overwrite", schema_mode="overwrite")            table = DeltaTable(path)            print(f"partition columns after: {table.metadata().partition_columns}")            print(f"version after: {table.version()}")            print(f"data files after: {delta_file_count(table)}")            print(f"rows after: {read_delta(path).num_rows}")            # version 2 is the last version before the rewrite; Delta counts versions from 0            old = DeltaTable(path, version=2)            print(f"partition columns in version 2: {old.metadata().partition_columns}")            print(f"rows in version 2: {read_delta(path, version=2).num_rows}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
输出python delta-partition-overwrite.py
partition columns before: ['day']
version before: 2
data files before: 3
change without schema mode: DeltaError: Generic error: Specified table partitioning does not match table partitioning: expected: ["day"], got: ["hour"]. To change partition columns, use full table overwrite with schema overwrite and no replaceWhere predicate.
partition columns after: ['hour']
version after: 3
data files after: 3
rows after: 1499
partition columns in version 2: ['day']
rows in version 2: 1499

The rewrite moves the table to a new version and keeps its rows. The three loads are versions 0 to 2, so the table is at version 2 before the change and 3 after the rewrite.

The new version holds the same 1499 rows in 3 files, one for each hour partition, which matches the three hours. Version 2 still reads back through read_delta, with its day partition and 1499 rows.

The Delta change is a rewrite of the table's current files, not a metadata edit. The table here is small. A large table needs the same rewrite at its own cost, so plan it as a maintenance task with a read window. Every row is also read into memory before the write, so the rewrite needs room for the whole table at once. For a table that does not fit, a copy into a new location is the safer route, and chapter 9 shows how to check such a copy.

DuckLake stores partitioning as a table setting in its catalog, and a change applies to later loads only. The DuckLake documentation says the partitioning keys of a table affect only the data written after the change. Set the table to partition by hour(hour_utc), load one more hour, and the file counts before and after that load show the rule at work. The helper attaches the catalog with inlining off, so each load writes a data file, and the count shows what each load did.

ducklake-partition-alter.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通过
"""Set a DuckLake table's partitioning to hour, then load one more hour and count the files before and after it.The files-kept line is the one to check: it counts the earlier files still listed after the hour load."""from lib.lakehouse import (DUCKLAKE_ALIAS, NAMESPACE, TABLE, connect_ducklake, create_ducklake_table, ducklake_file_count,                           ducklake_file_paths, new_warehouse, read_cut_hour, safe_error)def load(con, hour):    con.register("batch", read_cut_hour(hour))    con.execute(f"INSERT INTO {DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE} SELECT * FROM batch")    con.unregister("batch")def main():    try:        with new_warehouse() as wh:            con = connect_ducklake(wh.con)            # the helper leaves inlining off by default, so every load below writes one data file            create_ducklake_table(con, wh.root)            for hour in range(3):  # hours 00 to 02, before the change                load(con, hour)            print(f"data files before the change: {ducklake_file_count(con, DUCKLAKE_ALIAS, TABLE)}")            before = ducklake_file_paths(con, DUCKLAKE_ALIAS, TABLE)            con.execute(f"ALTER TABLE {DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE} SET PARTITIONED BY (hour(hour_utc))")            load(con, 3)  # hour 03, the first load after the change            print(f"data files after one load under hour: {ducklake_file_count(con, DUCKLAKE_ALIAS, TABLE)}")            after = ducklake_file_paths(con, DUCKLAKE_ALIAS, TABLE)            # the intersection is the earlier files still listed after the hour load            print(f"files kept from before the change: {len(before & after)}")            # ordered by key index, so the keys print in a fixed order            for key, transform in con.execute(                "SELECT partition_key_index, transform FROM __ducklake_metadata_lake.ducklake_partition_column ORDER BY 1"            ).fetchall():                print(f"partition key {key}: transform {transform}")            rows = con.execute(f"SELECT count(*) FROM {DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}").fetchall()            print(f"rows in table: {rows[0][0]}")  # count(*) returns one row with one value    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
输出python ducklake-partition-alter.py
data files before the change: 3
data files after one load under hour: 4
files kept from before the change: 3
partition key 0: transform hour
rows in table: 1999

The table had 3 data files before the hour load and 4 after it, so the hour load wrote one file. Of the files listed after that load, 3 were already listed before it. The three earlier loads were not rewritten, which is what the documentation's rule means in practice. The catalog lists one partition key, with the transform hour, and the table holds 1999 rows.

Working rule: In Iceberg and DuckLake, a partition change is a change to metadata. Old files stay in place and later loads use the partitioning the change set, so check the file counts after the first load. In Delta Lake, a partition change is a full overwrite that rewrites the table's current files, so plan it as a rewrite and check the row count and the file count after it.

生产环境中会出什么问题

最近一次修改见于版次 2026.11.7

分区变更本身很少出错;问题往往在之后的加载和查询计划中才显现出来。

先说缺少软件包的情况。在关于迁移到按小时分区的一节所列的版本固定下,按天和按小时的转换需要 pyiceberg-core,而这些转换在写入时会导入它。如果环境中只安装了 pyiceberg,则可以创建表,但在时间转换下的第一次追加写入时就会失败。这一问题出现在第一次定时加载时,而不是在修改分区规范时,所以版本固定应当写进依赖文件,而不是依赖某个人对安装过程的记忆。

其次是过度分区。分区粒度比过滤条件所需的更细,会使每次查询要打开更多文件,而每个文件包含的行数更少。每小时加载几百行,得到的文件按绝对大小来看都很小。这是经验法则,不是测量结果:代价取决于你的存储和引擎。关于查询扫描内容的一节中的计划计数显示了在每种分区规范下一次查询会打开多少个文件。如果全表扫描的文件数随每次加载不断增长,而每个文件的行数仍然很少,就说明出现了这一问题。解决办法是合并小文件(compaction,第 6 章会讲到),或者对之后的加载采用更粗的粒度。

第三是高基数的键。对 page_title 做恒等分区,会使每个标题对应一个分区,而每次加载都会为其中包含的每个标题写入一个文件。这里的表只有几千行,但真实的页面表的标题数远多于此,文件数会随标题数增长,而不是随时间增长。应按时间(过滤条件所用的列)来分区,并将标题保留为一列,供查询对其进行过滤。

再来是仅凭结果来判断变更。分区变更前后的行是相同的,因此无论变更是否带来实际好处,只比较行的检查都会通过。本章的示例打印这些行,只是为了确认没有丢失任何数据。真正能体现变更效果的是计数。

最后是对读者正在使用的表执行重写。本章中的 Delta 示例是单独运行的,并没有在写入期间测试读者。对于读者依赖的表,我们建议把重写结果写入一个副本,检查副本的计数和行,然后再让读者指向它。第 9 章在不同格式之间使用同样的检查。这一建议出自判断,没有示例对其进行测量。

工作准则: 应根据读者所用的过滤条件和预期的文件大小来选择分区粒度,而不是根据数据到达的频率。对服务于读者的表执行分区变更之前,先在副本上运行,并比较两侧的计划计数和行数。

本章做出的决定

最近一次修改见于版次 2026.11.8
  • 我们按 hour_utc 的 day 和 hour 转换对 Iceberg 表分区,并将 pyiceberg-core 与 pyiceberg 的版本固定在一起。这些转换把时间列保留为分区源,因此按时间过滤时读取的字段与写入方所用的字段相同。对于任何按时间过滤的表,我们都推荐这样做。
  • 我们用 schema_mode="overwrite" 做一次完整覆盖来修改 Delta Lake 表,并把它的分区列写成由写入方计算的普通字符串列 day 和 hour。我们接受这次重写,因为在这个库中,更改分区需要完整覆盖。
  • 我们通过各个库自带的列举方式来统计文件和计划:Iceberg 用 plan_files(),Delta Lake 用 file_uris(),DuckLake 用 ducklake_list_files。没有任何示例打印文件名,因为文件名中含有随机 ID,每次运行都不相同。
  • 对每个统计文件数的示例,我们都关闭 DuckLake 的内联,如第 1 章所述,这样文件数统计的就是数据文件的数量。
  • 我们根据仪表板的过滤条件(每次读取一个小时)来选择以小时为粒度,而不是根据数据加载的到达频率。
  • 我们先展示 Delta 的失败,再展示修复方法,这样要求设置模式的那个错误就能说明该模式设置的由来。
  • 我们从目录的分区表而不是文件名中打印 DuckLake 的分区键,因此文件名变化时,输出不会随之改变。
  • 我们在输出中保留字段和规格的标签,从不打印规格 ID、快照 ID 或文件名。快照 ID 和文件名每次运行都不同,而标签无需读者解读 ID,就能说明某个规格属于哪个时期。

本章,在本版次中

版次 2026.11.10示例于 2026年11月20日 通过本章 4个示例 个示例中有 4 个通过

译自英文版图书,版次 2026.11.10。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 4 章,共 10 章: 在不重写旧文件的情况下更改分区

  1. 分区规范同样有版本
  2. 从按天分区迁移到按小时分区
  3. 各规格下写入的文件
  4. 检查查询扫描了什么
  5. Partitioning in the other formats
  6. 生产环境中会出什么问题
  7. 本章做出的决定

返回顶部全部章节