古いファイルを書き換えずにパーティショニングを変更する

読了まで約35 分分、7 節 節の 4 例 例。

第2026.11.10版 2026年11月20日時点で例が通過 39 例中 39 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.10)から翻訳した。 原文を読む

本章では、Iceberg、Delta Lake、DuckLake のテーブルでパーティショニングを変更し、変更の前後でクエリが計画するファイルの数を数える。パーティショニングはクエリがどのファイルを開くかを決めるため、これを変更すると、すべての読み手が支払うコストが変わる。すでに書き込まれたファイルにどのような影響が出るかは、フォーマットによって異なる。

wiki.pageviews_hourly のダッシュボードは1時間単位でデータを読む。このテーブルは日単位でパーティション分割されており、すでに読み込んだデータを書き換えずに、時間単位へ再分割する方法が問題となる。冒頭の3回の時間単位のロードは、すでにディスク上にある。そこでチームは、02時より後のすべてのロードに時間パーティションを適用したいと考えている。同時に、既存の3回分のロードをコピーせずに、変更がそれらにどのような影響を与えるかを知る必要がある。

この変更には2つのコストがある。1つ目は変更そのものの作業であり、フォーマットが古いファイルをそのままにするかどうかで決まる。2つ目は以後のすべてのクエリが支払うコストである。変更をまたぐクエリは、両方の時期のファイルを計画に含めるためである。本章では、各ライブラリが返す件数でこの2つを測定する。これにより、フォーマットの説明ではなく、テーブルの実際の挙動に基づいて判断できる。

パーティション仕様もバージョン管理される

最終変更:版2026.11.7

パーティション仕様は、テーブルが行をどのようにグループ化するかを定めるものである。例えば、hour_utc の日ごとに1グループとする仕様がある。Iceberg では、仕様はテーブルのメタデータの一部であり、各データファイルを列挙するマニフェストには、そのファイルが書き込まれたときの仕様が記録される。仕様を変更すると、独自の ID を持つ2つ目の仕様ができる。以後の書き込みは2つ目の仕様を使い、すでにディスク上にあるファイルは、書き込まれたときの仕様のままである。Iceberg specification によれば、変更後の仕様は一意の仕様 ID を付けてテーブルのパーティション仕様の一覧に追加され、各マニフェストは、自身の書き込みに使われた仕様の ID を記録する(partition_spec_id)。

これにより、テーブルには2つのパーティション分割の時代が並んで存在することになる。クエリは開いた各ファイルの仕様を読むので、1回のスキャンが複数の仕様のファイルにまたがることがある。これはプランナが処理してくれるため、変更のコストは、クエリが返す行ではなく、実行計画とファイル数に現れる。hour_utc に対して書かれたクエリは、仕様が変わってもそのテキストを変えずに済む。これがこの設計の狙いである。変わるのは、プランナが開くファイルの集合である。この章の以降の部分で、その両方を示す。

仕様の変更はメタデータのみの操作である。Iceberg は独自の ID を持つ仕様を書き込み、データファイルには手を加えない。このことは、次の節のファイル数が示している。

古い仕様も履歴として残る。テーブルはこれまでに持ったすべての仕様の記録を保持するため、読み手は、あるファイルがどのフィールドで書き込まれたかをいつでも調べられる。パーティション分割を複数回変更するチームにとって、これは重要である。各ファイルは「自分はどのように分割されたか」という問いに自身の仕様で答えるので、変更の順序を誰も覚えておく必要がない。この記録はメタデータなのでコストは小さいが、テーブルの仕様の一覧は変更のたびに増えていく。

他の2つのフォーマットは、パーティション分割の扱いが異なり、その違いが変更のコストを決める。Delta Lake はパーティション列を名前で受け取るため、書き込み側がそれらを列として作成する。DuckLake はパーティションキーをカタログに保持する。それぞれの扱いは、この章の以降の部分が依拠する Iceberg の手順のあとに置いた、他のフォーマットの節で説明する。

実践ルール: Iceberg のパーティション仕様を変更するのは、読み手のフィルタが変わり、現在の仕様ではそのフィルタに対して計画されるファイルが多すぎる場合である。現在の仕様がそれらのフィルタに対してすでに少数のファイルしか計画しないのであれば、変更しない。変更する場合は、古いファイルをそのままにしておく。変更の日付、古いフィールドと置き換え後のフィールド、変更のきっかけとなった読み手のフィルタを、テーブルのランブックに記録する。変更の前後の計画数も、あわせて保存する。その方法は、クエリが何をスキャンするかについての節が示している。

この部分はまだ翻訳されていないため、英語で表示している。

Move from daily to hourly partitions

最終変更:版2026.11.10

Each example builds its table from the cut again, with the original columns and not the ones chapter 3 added. To move the table to hours, you swap one transform of hour_utc for another. Iceberg partitions by a transform of a column: the day transform puts each row under its calendar day, and the hour transform puts each row under its hour. The pyiceberg library computes these transforms with the pyiceberg-core package, and the day transform imports that package when it writes. An install with only pyiceberg therefore fails at the first append under a day or hour partition (pyiceberg 0.12.0 source, pyiceberg/transforms.py, DayTransform.pyarrow_transform). The pins in this book include pyiceberg-core at 0.11.0, next to pyiceberg at 0.12.0.

The table starts with a day spec. Hours 00 to 02 load under it. Then the spec changes, and hours 03 to 05 load under the hour spec. The change is one update_spec() block that removes the day field and adds the hour field:

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

Both calls go in one block, so the table gets one spec change with the day field gone. The spec list, printed in order with the transform of each field, shows what the change did. The field names are the ones this book uses, ts_day and ts_hour, so a spec label says which transform each field applies. The source column stays hour_utc. The day field and the hour field are two transforms of that column, so a reader's filter on the column keeps working across both eras.

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

Read the output from the top. Spec 1 has one field, ts_day, with the day transform. Spec 2 has one field, ts_hour, with the hour transform. The table's rows are all there after the change: 2999 rows, which is the three hours before the change and the three after it.

The spec change is the only step that touches the metadata alone. The loads on either side of it write data files as usual, and the next subsection shows which spec each file belongs to.

A mistake here shows up later, not in the change itself. If the spec list is wrong, every load after the change writes files under the wrong partitioning, and the counts in the next section are the first place you see it. Checking the spec list right after the change costs one line of output and saves a rewrite.

Working rule: In Iceberg, make the spec change in one update_spec() block, so the old field is removed in the same change that adds the replacement. Split the two edits only if a step has to run between them; this chapter has no such step. Check the spec list after the change, and check that the field names and transforms are the ones you meant before you load any data under the second spec.

各スペックの下で書き込まれたファイル

最終変更:版2026.11.8

各データファイルは、それが書き込まれたときのスペックに属する。したがって、スペックごとにファイルを数えれば、各ファイルがどの時期のものかが分かる。データファイルの一覧には各ファイルのスペック ID が含まれているので、ファイルをスペックごとにグループ化し、「spec 1」と「spec 2」というラベルの下でスペックごとに 1 つずつ件数を数えることができる。ラベルはスペックを作成された順に番号付けしたものであるため、出力にスペック ID は現れない。

日単位でパーティション分割された 3 回のロードは、変更後もファイルを保持していた。出力では、spec 1 の下に 3 個、spec 2 の下に 3 個のデータファイルが示されている。このことから、時単位でパーティション分割された 3 回のロードがそれぞれ独自のファイルを書き込んだこと、そしてスペックの変更そのものは何も書き込まなかったことが分かる。もし変更後に spec 1 の件数が減っていたなら、何かがそれらのファイルを書き換えたことになり、古い時期のデータを信頼する前に、その原因を突き止める必要がある。

実践ルール: スペックを変更したら、そのたびに各スペックの下のデータファイルを数え、その件数を実際に行ったロードと照らし合わせること。書き換えを予定していないのに件数が動いた場合、その変更は意図した以上の影響を及ぼしている。次のロードの前に、作業を止めて確認すること。

クエリがスキャンする対象を確認する

最終変更:版2026.11.10

パーティション仕様は、ファイルをスキップするための仕組みである。クエリがファイルを読む前に、プランナーはそのファイルのパーティション値と列の境界値を調べ、フィルタに一致しえないファイルを除外する。クエリが安く済む度合いは、プランに含めないファイルの多さで決まる。したがって、変更を確認するには、行を比較するのではなく、典型的なフィルタがプランに含めるファイルの数を、変更の前後で数えればよい。スキャンのプランニングは、行を読まずにファイルの一覧を返す。そのため、このファイル数は、変更のたびに実行できるほど低コストで得られる。

変更の効果が現れるのはプルーニングである。そこで、3つのスキャンを2回ずつプランニングする。1回目は日単位の仕様のもとで行い(時間単位のパーティションへの移行を参照)、2回目は時間単位でパーティション化された3回のロードの後に行う。2つのフィルタはそれぞれ1時間を指定する。1つは変更前にロードされた01時、もう1つは変更後にロードされた04時である。3つ目はフィルタを持たない全件スキャンである。

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
段階 1時間フィルタ 04時フィルタ フィルタなし
変更前、日単位パーティションの3回のロード 1 0 3
変更後、時間単位パーティションの3回のロードを追加 1 1 6

どのフィルタも、その時間がどの時期にロードされたかにかかわらず、その時間自身のファイルに到達する。1時間フィルタのプランに含まれるファイルは、変更前が1個、変更後が1個である。04時フィルタのプランに含まれるファイルは、変更前が0個、変更後が1個である。01時は変更前にロードされたため、両方のプランに含まれる1つのファイルは、その時間の日単位パーティションのファイルである。変更前は、3つのファイルがすべて同じ日を共有するため、プランナーが残る2つをスキップできる根拠はhour_utcの境界値だけである。変更後は、時間単位でパーティション化された3つのファイルも、パーティション値によってスキップされる。04時はこれとは逆に働く。日単位パーティションのファイルには04時のデータが含まれないため、一致するのは、その時間を保持する時間単位パーティションのファイルだけである。このファイル数からは、プランナーがファイルをパーティション値でスキップしたのか、列の境界値でスキップしたのかは分からない。分かるのは、プランが何を残したかだけである。

プランのファイル数は、ファイルの数であってバイト数ではない。ファイルごとにサイズが異なるため、同じ数のプランでも読み込まれるデータ量は異なりうる。それでも、ファイル数はプランナーが判断の基準にする数値であるから、最初の確認として適切である。ファイル数が一致しているのにクエリが遅い場合は、ファイルサイズとクエリ自体を調べる。

全件スキャンは、テーブルが書き込んだすべてのファイルを読む。そのプランは、3個のファイルから6個へ増える。これは、日単位パーティションのファイルに時間単位パーティションのファイルが加わった結果である。この増加は、古いファイルをそのまま残すことのコストであり、フィルタ付きのスキャンに加えて全件スキャンも数える理由である。

実践ルール: パーティションを変更する前後には、読み手が使うフィルタと全件スキャンをプランニングし、そのファイル数を運用手順書の記録とともに残す。1つのファイルしかプランに含まれなかったフィルタが多数のファイルを含むようになった場合、その変更はそのフィルタのプルーニングを壊している。その仕様のもとで次のロードを行う前に、仕様かフィルタを変更する必要がある。

その他のフォーマットにおけるパーティショニング

最終変更:版2026.11.10

他の二つのフォーマットでは、同じ変更に別のコストがかかる。ただし、読み戻される行は三つのフォーマットで同じである。変わるのはファイルと実行計画である。次の表は三つのフォーマットをまとめたものである。

フォーマット 変更の方法 書き込み済みのファイル 変更後に確認すること
Iceberg update_spec() ブロック一つ そのまま残り、古いスペックの下に置かれたままになる スペックごとのファイル数、プランの件数
Delta Lake schema_mode="overwrite" を指定した全体の上書き 後のバージョンで書き直される。古いバージョンは残る 行数、ファイル数、古いバージョンのパーティション列
DuckLake ALTER TABLE ... SET PARTITIONED BY そのまま残り、設定は以降のロードに適用される 1回のロード後のファイル数、パーティションキー

Delta Lake はプレーンな列でパーティショニングし、そのパーティションオプションは式ではなく列名を受け取る。Delta Lake のプロトコルは partitionColumns を、データのパーティショニングに使う列名を含む配列として定義している。生成列を使えばテーブル内部で day や hour を計算できるが、その場合テーブルのライタープロトコルが引き上げられる。そのため本書では両方をライター側で計算する。ヘルパー with_partition_columns は、書き込みのたびに hour_utc から二つの文字列列を追加する。テーブルは最初 day でパーティショニングされており、hour への変更は、スキーマも置き換える全体の上書きでない限り拒否される。

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.

まず単純な mode="overwrite" で変更を試すと、ライブラリはそのエラーで変更を拒否する。同じ書き込みに schema_mode="overwrite" を付けると通る。これは、固定した版のライブラリの API が、従来の overwrite_schema フラグの代わりに使う設定である。上書きの開始前に行をメモリへ読み込むのは、上書きがテーブルの保持するすべての行を置き換えるからである。行を残すには、書き戻すしかない。

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

書き直しによってテーブルは新しいバージョンに移り、行は保たれる。三回のロードがバージョン 0 から 2 にあたるため、テーブルは変更前がバージョン 2、書き直し後がバージョン 3 になる。

新しいバージョンは、同じ 1499 行を 3 個のファイルに保持する。ファイルは時間パーティションごとに一つあり、三つの時間に一致する。バージョン 2 は引き続き read_delta で読み戻すことができ、day パーティションと 1499 行を持つ。

Delta での変更は、メタデータの編集ではなく、テーブルの現在のファイルの書き直しである。ここでのテーブルは小さい。大きなテーブルでも同じ書き直しが必要で、そのコストはテーブルの大きさに応じてかかる。そのため、読み取りの時間枠を設けた保守作業として計画する。また、書き込みの前にすべての行をメモリへ読み込むので、書き直しにはテーブル全体を一度に収める余裕が要る。収まらないテーブルでは、新しい場所へのコピーがより安全な方法であり、そのコピーの確認方法は第9章で示す。

DuckLake はパーティショニングをカタログ内のテーブル設定として保存し、変更は以降のロードにのみ適用される。DuckLake のドキュメントは、テーブルのパーティショニングキーが変更後に書き込まれるデータにのみ影響すると述べている。テーブルを hour(hour_utc) でパーティショニングするよう設定し、さらに1時間分をロードすると、そのロードの前後のファイル数がこの規則の働きを示す。ヘルパーはインライン化を無効にしてカタログをアタッチするので、各ロードがデータファイルを書き出し、その数から各ロードの動作が分かる。

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

テーブルのデータファイルは、時間のロードの前が 3 個、後が 4 個であり、hour のロードで書き出されたファイルは一つだった。そのロード後に一覧されたファイルのうち、3 個はロード前にも一覧されていた。以前の三回のロードは書き直されておらず、これがドキュメントの規則の実際の意味である。カタログには変換 hour を持つパーティションキーが一つ記載され、テーブルは 1999 行を保持している。

実践ルール: Iceberg と DuckLake では、パーティションの変更はメタデータの変更である。古いファイルはそのまま残り、以降のロードは変更で設定されたパーティショニングを使うので、最初のロード後にファイル数を確認する。Delta Lake では、パーティションの変更はテーブルの現在のファイルを書き直す全体の上書きなので、書き直しとして計画し、その後に行数とファイル数を確認する。

本番環境で起きる問題

最終変更:版2026.11.7

パーティションの変更は、変更そのものでは失敗することが少ない。問題は、その後のロードやプランに現れる。

まず、パッケージの欠落がある。1時間単位のパーティションへの移行に関する節で示したバージョン固定の下では、day 変換と hour 変換に pyiceberg-core が必要であり、これらの変換は書き込み時にそれをインポートする。pyiceberg だけをインストールした環境では、テーブルを作成できるが、時間変換の下での最初の追記で失敗する。この失敗が表面化するのは、スペックを変更したときではなく、最初の定期ロードのときである。そのため、バージョン固定は、インストール時の記憶ではなく、requirements ファイルに書いておくべきである。

次に、過剰なパーティション分割がある。フィルタが必要とする粒度よりも細かいパーティション粒度では、クエリごとに開くファイルが増え、各ファイルが持つ行数は少なくなる。数百行ずつの1時間単位のロードでは、絶対的に小さなファイルができる。これは測定ではなく経験則である。コストは、ストレージとエンジンによって異なる。クエリが走査する対象に関する節のプラン数を見ると、各スペックの下でクエリが開くファイルの数が分かる。ロードのたびにフルスキャンのファイル数が増え続け、ファイルあたりの行数が小さいままであれば、それが兆候である。対処は、コンパクション、または以降のロードでより粗い粒度を採用することである。コンパクションは第6章で扱う。

3つ目は、カーディナリティの高いキーである。page_title に対する identity パーティションは、タイトルごとに1つのパーティションを作り、各ロードは、それに含まれるすべてのタイトルについてファイルを書き込む。ここでのテーブルは数千行だが、実際のページテーブルにはそれよりはるかに多くのタイトルがあり、ファイル数は時間ではなくタイトルに従って増える。フィルタが使う時間でパーティションを分け、タイトルは、クエリがフィルタをかける列として残すのがよい。

さらに、結果によって変更を判断することがある。パーティション変更の前後で行は同じであるため、行を比較する検査は、変更が役に立ったかどうかにかかわらず通ってしまう。この章の例が行を出力するのは、何も失われていないことを確認するためだけである。変更を示すのは件数である。

最後に、読み手が使っているテーブルに対して書き換えを実行することがある。この章の Delta の例は単独で実行されており、書き込み中の読み手についてはテストしていない。読み手が依存するテーブルでは、書き換えをコピーに対して行い、コピーの件数と行を確認してから、読み手の向き先をコピーに切り替えることを勧める。第9章では、フォーマット間で同じ確認を用いる。これは判断に基づく推奨であり、それを測定した例はない。

実践ルール: パーティション粒度は、データが到着する頻度ではなく、読み手が使うフィルタと、想定するファイルの大きさから選ぶ。読み手が利用しているテーブルでパーティション変更を実行する前に、コピーに対して実行し、両側でプラン数と行数を比較する。

この部分はまだ翻訳されていないため、英語で表示している。

Decisions this chapter made

最終変更:版2026.11.8
  • We partition the Iceberg table by the day and hour transforms of hour_utc, and pin pyiceberg-core beside pyiceberg. The transforms keep the time column as the partition source, so a filter on time reads the same field the writer used. We recommend this for any table that filters on time.
  • We change the Delta Lake table by a full overwrite with schema_mode="overwrite", and we write its partition columns as plain string columns, day and hour, computed by the writer. We accept the rewrite, because in this library a partition change needs a full overwrite.
  • We count files and plans through each library's own listing: plan_files() for Iceberg, file_uris() for Delta Lake and ducklake_list_files for DuckLake. No example prints a file name, because the names hold a random ID that differs on every run.
  • We turn off DuckLake's inlining for every example that counts files, as chapter 1 explains, so a count of files is a count of data files.
  • We choose the hour grain from the dashboards' filters, which read one hour at a time, and not from how often loads arrive.
  • We show the Delta failure first, then the fix, so the schema setting is explained by the error that asks for it.
  • We print the DuckLake partition key from the catalog's partition table, not from file names, so the output does not change when the file names do.
  • We keep the field and spec labels in the output and never print a spec ID, a snapshot ID or a file name. Snapshot IDs and file names differ from one run to the next, and a label says which era a spec belongs to without the reader decoding its ID.

この版における本章

第2026.11.10版2026年11月20日時点で例が通過この章の4 例件のうち4件が合格

英語版の書籍(版2026.11.10)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全10章中の第4章: 古いファイルを書き換えずにパーティショニングを変更する

  1. パーティション仕様もバージョン管理される
  2. Move from daily to hourly partitions
  3. 各スペックの下で書き込まれたファイル
  4. クエリがスキャンする対象を確認する
  5. その他のフォーマットにおけるパーティショニング
  6. 本番環境で起きる問題
  7. Decisions this chapter made

ページの先頭に戻るすべての章