削除・更新・マージで行を訂正する
読了まで約33 分分、9 節 節の 5 例 例。
すでにコミットされた行も変更できる。この章では、Iceberg、Delta Lake、DuckLake で行の削除、upsert、マージを行い、各書き込みがファイルに何をもたらすかを説明し、pyiceberg の upsert が追加するスナップショットの数を数える。
ここまでは、テーブルは増える一方である。第1章のすべての書き込みは wiki.pageviews_hourly に追加するものであり、このテーブルには、ソースが1時間分のデータを再配信することがある。
遅れて届くデータは訂正として届く
第1章のテーブルに届いた02時の最初の配信には、そのときソースが送った件数が入っている。同じ時間の後の配信には、一部のページについて訂正された件数と、最初の配信に含まれていなかった1ページが入っている。訂正に含まれるページは以前と同じページであるから、テーブルは行をその場で変更する必要がある。訂正された時間を追記すると、すべてのページが古い件数と新しい件数の2通りで二重に保存されてしまう。
本書では、行はそのキーによって識別される。キーは hour_utc、domain_code、page_title の組である。訂正とはキーを持つ行の集合であり、各キーについて、テーブルがすでに行を保持していれば変更し、保持していなければ追加する。したがって訂正の書き込みはキーに関する問題であり、書き込みは次の一つの規則でそれに答える。すなわち、キーは書き込むバッチの中でちょうど一つの行を識別しなければならない。pyiceberg と DuckLake はどちらもこの規則を強制する。この章では、deltalake のマージでキーの重複を試すことはしない。
訂正は通常、数行ではなく時間全体が再配信される形で届く。時間全体を送ればバッチは自己完結する。書き込みが何が変わったかを行ごとに判断するからである。その代償として、訂正された行だけでなく、その時間のすべての行が比較される。すべての行を比較するので、pyiceberg は値が異なる行だけを数えることができ、同じバッチを再実行しても何も変わらない。
ここでの訂正はコードで作成し、第1章の実データの切り出しを元にする。ヘルパー hour_corrections は、02時の20件のページタイトルについて件数を半分にし、小数点以下を切り捨てる。遅れて届く行は、その時間の最初の行のコピーであり、最初の配信にはなかったページタイトルを持つ。生成するのは訂正バッチだけであり、pageviews の行は第1章で切り出したものである。
実践ルール: 訂正を書き込む前に、そのバッチが各キーをちょうど一度だけ含んでいることを確認する。pyiceberg と DuckLake は、キーが重複したバッチをそれぞれのやり方で拒否し、再試行してもデータは直らない。失敗の例は本番運用の節で示す。
この部分はまだ翻訳されていないため、英語で表示している。
Delete rows, and what each format writes
A delete removes the rows that match a predicate. The rows go away in every format, but the files that held them can be handled in two ways. In copy-on-write, the writer rewrites each data file that held a matching row and leaves out the deleted rows. In merge-on-read, the writer leaves the data file alone and writes a delete file that records which rows are gone. Readers apply the delete file when they scan.
The two libraries take the predicate in different forms. pyiceberg takes an expression object, built here from EqualTo and LessThan. deltalake takes a SQL string, which reads like the WHERE clause a reader already knows. The delete below uses both forms on the same rows, so you can compare them directly.
The delete removes the hour 02 rows with fewer than 180 views, a threshold this chapter chose. The cut in chapter 1 keeps only the most-viewed rows in each hour, so a predicate for fewer than two views matches nothing. pyiceberg then warns with UserWarning: Delete operation did not match any records and writes no snapshot, as its source shows. A threshold of 180 catches a few of the least-viewed rows in hour 02, which is enough to show what a delete writes.
1"""Runs one delete through Iceberg, Delta Lake and DuckLake and prints what each format removed and rewrote. The data-file lines carry the point; the deleted-row lines beside them are for comparison."""23from datetime import datetime45from deltalake import DeltaTable6from pyiceberg.expressions import And, EqualTo, LessThan78from lib.lakehouse import DUCKLAKE_ALIAS, NAMESPACE, TABLE, ducklake_file_count, load_three_formats, new_warehouse, read_delta, safe_error, scan_arrow910HOUR_02 = datetime(2024, 6, 3, 2)11# A threshold, not a fact about the data: the cut keeps the most-viewed rows of each hour, so a small one would match nothing.12LOW_VIEWS = 180131415def main():16 with new_warehouse() as wh:17 iceberg, delta_path, lake = load_three_formats(wh, range(6)) # hours 00 to 05, one commit per hour in each format18 iceberg_before = scan_arrow(iceberg).num_rows19 delta_before = read_delta(delta_path).num_rows20 table = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"21 lake_before = lake.execute(f"SELECT count(*) FROM {table}").fetchall()[0][0]22 files_before = ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE) # counted before the delete, to compare with the count after2324 iceberg.delete(And(EqualTo("hour_utc", HOUR_02), LessThan("views", LOW_VIEWS)))25 summary = iceberg.current_snapshot().summary # the snapshot summary counts each data file the delete removed from the table26 print("Iceberg deleted rows:", iceberg_before - scan_arrow(iceberg).num_rows)27 print("Iceberg remaining rows:", scan_arrow(iceberg).num_rows)28 print("Iceberg data files rewritten:", summary["deleted-data-files"])2930 delta = DeltaTable(delta_path)31 # the hour is written as a timestamp string inside the SQL predicate32 metrics = delta.delete(f"hour_utc = '2024-06-03T02:00:00' AND views < {LOW_VIEWS}")33 print("Delta Lake deleted rows:", delta_before - read_delta(delta_path).num_rows)34 print("Delta Lake remaining rows:", read_delta(delta_path).num_rows)35 print("Delta Lake data files rewritten:", metrics["num_removed_files"])3637 lake.execute(f"DELETE FROM {table} WHERE hour_utc = TIMESTAMP '2024-06-03 02:00:00' AND views < {LOW_VIEWS}")38 lake_after = lake.execute(f"SELECT count(*) FROM {table}").fetchall()[0][0]39 print("DuckLake deleted rows:", lake_before - lake_after)40 print("DuckLake remaining rows:", lake_after)41 print("DuckLake data files before:", files_before)42 print("DuckLake data files after:", ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE))43 # a delete file is listed against the data file it applies to, so counting the listed rows that have one counts the delete files44 print("DuckLake delete files written:", lake.execute(45 f"SELECT count(*) FROM ducklake_list_files('{DUCKLAKE_ALIAS}', '{TABLE}', schema => '{NAMESPACE}') "46 "WHERE delete_file IS NOT NULL").fetchall()[0][0])474849if __name__ == "__main__":50 try:51 main()52 except Exception as exc: # the redacted error is what a reader sees53 print(safe_error(exc))54 raise SystemExit(1)
python delete-low-views.pyIceberg deleted rows: 4
Iceberg remaining rows: 2995
Iceberg data files rewritten: 1
Delta Lake deleted rows: 4
Delta Lake remaining rows: 2995
Delta Lake data files rewritten: 1
DuckLake deleted rows: 4
DuckLake remaining rows: 2995
DuckLake data files before: 6
DuckLake data files after: 6
DuckLake delete files written: 1
All three formats delete the same number of rows: 4 in Iceberg, 4 in Delta Lake and 4 in DuckLake, but the files they rewrite differ.
Iceberg rewrote 1 data file, the one that held hour 02, and leaves 2995 rows. Delta Lake removes the same rows, leaves 2995, and rewrote 1 file. Both formats rewrote the file for hour 02 and left the other five hours alone, because a file is the unit a copy-on-write delete replaces.
DuckLake's DELETE leaves 2995 rows and rewrites no data file. Its data files stay at 6 before the delete and 6 after it, and the delete writes 1 delete file.
The cost of the Iceberg and Delta Lake deletes follows the size of the files they touch, not the number of rows they remove. 4 rows went, and 1 whole file was rewritten to remove them. A table whose matches are spread across many files pays for each of those files. So the cost depends on where the matching rows sit.
Each library reports its own counts, and this example computes the deleted rows as the rows before minus the rows after, so the deleted and remaining counts agree by construction. The rewritten-file counts come from the library: the Iceberg snapshot summary's deleted-data-files and the num_removed_files metric that deltalake returns from delete.
Copy-on-write と merge-on-read
この二つの書き込み方式は、コストを書き込み側と読み取り側のどちらが負うかが異なる。Copy-on-write は書き込みのコストを高くし、読み取りのコストを低くする。読み取り側は、ファイルが保持する行をそのまま受け取り、適用する処理は何もない。Merge-on-read は、削除された行の位置だけを書き込むため、書き込みのコストが低い。その代わりに、データファイルが書き換えられるまで、コストは読み取り側に移る。
この章で扱う三つのフォーマットの違いは次のとおりである。
| フォーマット | 固定したバージョンのライブラリ | 固定したバージョンでライブラリが削除を書き込む方法 | この章での扱い |
|---|---|---|---|
| Iceberg | pyiceberg 0.12.0 | Copy-on-write。delete は、条件に一致する行を含むデータファイルを書き換え、削除ファイルは書き込まない。write.delete.mode を merge-on-read に設定すると、pyiceberg は "Merge on read is not yet supported, falling back to copy-on-write" と警告する(出典)。 |
あり。削除の例で示す |
| Delta Lake | deltalake 1.6.6 | Copy-on-write。一致する行を含むファイルが書き換えられ、ログには古いファイルが削除されたものとして記録される。 | あり。削除の例で示す |
| DuckLake | DuckDB 2.0.0 | Merge-on-read。DELETE は削除ファイルを書き込み、データファイルはそのまま残す。 |
あり。削除の例で示す |
DuckLake の行は、削除の例で示される。この例では、削除ファイルと、そのまま残るデータファイルを数える。DuckLake の deletion vector に関するドキュメントは、削除された行の位置を .puffin ファイルに記録する実験的なオプションを説明している。このオプションは既定では無効であり、この章では有効にしない。削除ファイルを経由して読み取るコストは、ここでは測定しない。merge-on-read のテーブルの読み取り側は、データファイルが書き換えられるまで、スキャンのたびにそのコストを負う。そのため、読者自身のテーブルで測定すること。
Delta Lake にも、削除された行の位置をファイルに記録する deletion vector がある。これは Delta における merge-on-read の選択肢であり、第三の書き込み方式ではない。本書では使用しない。固定したバージョンでは、deltalake 1.6.6 は deletion vector を書き込まない。この機能を有効にしたテーブルに対して delete を実行しても、ファイルは書き換えられる。Delta プロトコルは、テーブルが deletion vector を使う場合、そのテーブルのリーダー機能とライター機能の両方に deletion-vectors 機能を含めることを要求しており、この機能を有効にすると両方に追加される。本書がすべての Delta の読み取りに使う QueryBuilder は、そのようなテーブルを読み取れる。to_pyarrow_table と to_pyarrow_dataset は、テーブルがこの機能を宣言しているため、読み取りを拒否する。そのため本書ではこの機能を無効にしており、Delta の削除は copy-on-write になる。
実践ルール: Copy-on-write の削除では、一致する行を含むファイルごとにファイルの書き換えが必要になると見込むこと。一致する行が少数のファイルに収まる条件、たとえば 1 時間分のような条件を選び、あらかじめ分かっている削除は一回の書き込みにまとめること。Merge-on-read は、書き込みが頻繁で、データファイルが書き換えられるまで読み取り側が削除ファイルのコストを負担できるテーブルに向いている。
訂正された1時間分のアップサート
アップサートは、キーが一致する行を更新し、キーが一致しない行を挿入する。訂正には、この書き込みが適している。訂正された1時間分のデータには、テーブルに既にあるキーが含まれており、遅れて届いた行には、テーブルにまだないキーが含まれているからである。単純な追記では、訂正された行が元の行と並んで保存されるため、その時間帯のすべてのページが2回ずつ現れることになる。
次の2つの小節では、同じバッチを使って、pyiceberg のメソッドと DuckLake の SQL の MERGE を示す。
キーは、変更の適用先となる行を特定し、さらに、入ってくる2つの行が同じ行であるかどうかを決める。キーが狭すぎると、実際には別の行である2つが1つにまとめられ、広すぎると、同じ行の2つ目のコピーが挿入される。ここでのキーは hour_utc、domain_code、page_title であり、これは 第1章で、切り出しによって各行に与えられる識別子である。例に使うバッチでは、各キーは1回ずつしか現れない。
pyiceberg における upsert
pyiceberg の upsert は、行を持つ Arrow テーブルと、キーを構成する列を受け取る。キー列は join_cols として渡す。戻り値は、更新した行数と挿入した行数である。行が更新として数えられるのは、キー以外の列が変化した場合に限る。したがって、テーブルと同一の行は更新として数えられない。ただし、変更された行が同じファイルに含まれている場合、copy-on-write ではそのような行も書き直される。
訂正した時間帯の行と遅れて届いた行を 1 回の upsert で送り、その呼び出しがテーブルの履歴に何を残すかを数える。
1"""Upserts the corrected hour 02, with its late row, into the Iceberg table, then upserts the same batch again. The snapshot lines carry the point, in the order the commits were made."""23import pyarrow as pa45from lib.lakehouse import KEY, hour_corrections, load_three_formats, new_warehouse, read_cut_hour, safe_error, snapshot_labels678def main():9 with new_warehouse() as wh:10 iceberg, _, _ = load_three_formats(wh, range(6))11 before = {snapshot.snapshot_id for snapshot in iceberg.snapshots()} # so the loop below lists only the snapshots this upsert adds12 # hour_corrections halves the views of the first 20 page titles in byte order, so the same titles change on every run13 corrected = hour_corrections(read_cut_hour(2))14 # A late row: a page the first delivery of hour 02 did not have.15 late = corrected.slice(0, 1).set_column(16 corrected.schema.get_field_index("page_title"),17 "page_title",18 pa.array(["Late_arrival_example"], type=pa.string()),19 )20 batch = pa.concat_tables([corrected, late])2122 result = iceberg.upsert(batch, join_cols=list(KEY)) # KEY is the three key columns; a row matches when all three are equal23 # rows_updated counts only rows whose non-key values changed, so identical rows are not counted24 print("rows updated:", result.rows_updated)25 print("rows inserted:", result.rows_inserted)2627 iceberg.refresh()28 labels = snapshot_labels([snapshot.snapshot_id for snapshot in iceberg.snapshots()]) # snapshot IDs change on every run, so the labels number commits29 added = [snapshot for snapshot in iceberg.snapshots() if snapshot.snapshot_id not in before]30 for snapshot in added:31 label = labels[snapshot.snapshot_id]32 print(label, snapshot.summary.operation.value)33 # a snapshot that adds or deletes no records has no such key, so the count is 034 print(f"{label} records added:", snapshot.summary.get("added-records") or 0)35 print(f"{label} records deleted:", snapshot.summary.get("deleted-records") or 0)36 print("snapshots added:", len(added))3738 again = iceberg.upsert(batch, join_cols=list(KEY)) # the same batch again, as a retry would send it39 print("rows updated on second upsert:", again.rows_updated)40 print("rows inserted on second upsert:", again.rows_inserted)414243if __name__ == "__main__":44 try:45 main()46 except Exception as exc: # the redacted error is what a reader sees47 print(safe_error(exc))48 raise SystemExit(1)
python redeliver-hour-upsert.pyrows updated: 20
rows inserted: 1
snapshot 7 overwrite
snapshot 7 records added: 480
snapshot 7 records deleted: 500
snapshot 8 append
snapshot 8 records added: 20
snapshot 8 records deleted: 0
snapshot 9 append
snapshot 9 records added: 1
snapshot 9 records deleted: 0
snapshots added: 3
rows updated on second upsert: 0
rows inserted on second upsert: 0
1 回の upsert 呼び出しは 1 回のコミットではない。この例では 3 個のスナップショットが書き込まれ、20 行が更新され、1 行が挿入された。スナップショット一覧には、各スナップショットが記録した内容が表示される。
最初のスナップショットは overwrite である。このスナップショットは、hour-02 のファイルの行である 500 行を削除し、そのうち 480 行を変更せずに書き戻す。続く 2 つは append である。2 番目は変更された 20 行を追加し、3 番目は遅れて届いた行である 1 行を追加する。ラベルは snapshot_labels から付くので、番号はコミット順を表す。
pyiceberg 0.12.0 のソースでは、upsert は、変更された行がある場合にのみ overwrite を呼び出し、新しい行がある場合にのみ、その新しい行に対して append を呼び出す。overwrite は、削除と追加の 2 つのスナップショットを書き込む。ライブラリは行も書き戻すため、最初のスナップショットを overwrite として記録する。このため、変更行と新規行の両方を含むバッチはスナップショットを 3 つ追加し、変更行のみのバッチは 2 つ、新規行のみのバッチは 1 つ追加する。数えるときは、ライブラリの呼び出しからではなく、スナップショット一覧から数える。
同じ upsert をもう一度実行しても、何も変わらない。更新行数は 0、挿入行数は 0 と報告される。2 回目の実行では、すべてのキーがすでに訂正後の値になっていることが確認される。そのため、訂正を 2 回送ってもテーブルが 2 回変わることはなく、これが再試行を安全にしている。
実践ルール: upsert は join_cols にキーを指定して使い、件数は戻り値から読み取る。スナップショットはスナップショット一覧から数え、1 回の呼び出しが 1 回のコミットになると仮定しない。最初の書き込みが反映されたかどうか不明なときは、同じバッチをもう一度実行し、2 回目の実行で更新が報告されないことを確認する。
DuckLakeにおけるMERGE
DuckLakeは、同じ訂正をSQLのMERGE文として受け付ける。MERGE文は、対象テーブル、元のバッチ、およびキーをON句で指定し、WHEN句のそれぞれが、一致した行または一致しなかった行をどう扱うかを定める。以下の文は、直後の例が実行するものである。
MERGE INTO lake.wiki.pageviews_hourly AS t
USING batch AS s
ON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_title
WHEN MATCHED AND t.views <> s.views THEN UPDATE SET views = s.views
WHEN NOT MATCHED THEN INSERT (hour_utc, domain_code, page_title, views, response_bytes)
VALUES (s.hour_utc, s.domain_code, s.page_title, s.views, s.response_bytes)
WHEN NOT MATCHEDの分岐はresponse_bytesも挿入する。この値はこの切り出しのすべての行で0であるため、遅れて届いた行の値も0になる。
AND t.views <> s.viewsという条件は重要である。この条件がなければ、MERGEは一致したすべての行を更新して数えるため、再実行のたびにそれらをすべて数え直すことになる。条件があれば、カウントがすでに一致している行は手を加えられず、数えられない。この条件なしで文を実行する例はないため、条件なしの再実行についての主張は、実測した件数ではなく、文の読み取りによるものである。
1"""Merges the corrected hour 02 and its late row into the DuckLake copy with a SQL MERGE, then runs the same MERGE again. The matched-row line splits the changed count into inserts and updates; the second changed-row line is the rerun."""23import pyarrow as pa45from lib.lakehouse import hour_corrections, load_three_formats, new_warehouse, read_cut_hour, safe_error67# The WHEN MATCHED condition is what keeps a rerun from counting matched rows that already agree.8MERGE = """9MERGE INTO lake.wiki.pageviews_hourly AS t10USING batch AS s11ON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_title12WHEN MATCHED AND t.views <> s.views THEN UPDATE SET views = s.views13WHEN NOT MATCHED THEN INSERT (hour_utc, domain_code, page_title, views, response_bytes)14 VALUES (s.hour_utc, s.domain_code, s.page_title, s.views, s.response_bytes)15"""161718def main():19 with new_warehouse() as wh:20 _, _, lake = load_three_formats(wh, range(6))21 corrected = hour_corrections(read_cut_hour(2))22 # a copy of the hour's first row, with a page title the table never held23 late = corrected.slice(0, 1).set_column(24 corrected.schema.get_field_index("page_title"),25 "page_title",26 pa.array(["Late_arrival_example"], type=pa.string()),27 )28 lake.register("batch", pa.concat_tables([corrected, late]))29 print("source rows:", lake.execute("SELECT count(*) FROM batch").fetchall()[0][0])30 # the join counts source rows whose key the table already holds, which splits the changes into inserts and updates31 matched = lake.execute(32 "SELECT count(*) FROM lake.wiki.pageviews_hourly AS t JOIN batch AS s "33 "ON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_title"34 ).fetchall()[0][0]35 print("source rows matched:", matched)36 # DuckDB returns one count for a MERGE, with updates and inserts added together37 print("rows changed by the merge:", lake.execute(MERGE).fetchall()[0][0])38 print("rows changed by the same merge again:", lake.execute(MERGE).fetchall()[0][0])39 print("rows in table:", lake.execute("SELECT count(*) FROM lake.wiki.pageviews_hourly").fetchall()[0][0])404142if __name__ == "__main__":43 try:44 main()45 except Exception as exc: # the redacted error is what a reader sees46 print(safe_error(exc))47 raise SystemExit(1)
python merge-correction-ducklake.pysource rows: 501
source rows matched: 500
rows changed by the merge: 21
rows changed by the same merge again: 0
rows in table: 3000
アップサートと同様に、このマージは再実行しても安全である。変更される行数は、1回目が21行、2回目が0行であり、テーブルは最終的に3000行、すなわち6時間分と遅れて届いた行を保持する。
変更行数は2種類の変更を合算したものなので、内訳を知るには元のバッチの大きさが必要になる。バッチの501行のうち、テーブルにすでにあるキーに一致するのは500行であり、一致しない行は遅れて届いた行だけである。挿入された行数は、元の行数から一致した行数を引いたもので、ここでは501から500を引いた値になる。更新された行数は、変更された行数から挿入された行数を引いたものである。一致した行数だけでは、どちらの数も得られない。
これらの例では、第1章で説明したとおり、DuckLakeはインライン化をオフにしてアタッチされているため、各ロードはカタログ内の行ではなくデータファイルを書き出す。マージのカウントは行数に対するものである。
実践ルール: MERGEは、更新する列を比較するWHEN MATCHED AND条件を付けて書き、再実行しても何も変わらないようにする。実行する前に、元のデータが各キーを1回だけ持つことを確認する。DuckLakeは、1つの対象行を2つの元の行に対応させるマージを拒否する。そのエラーは本番運用の節に示してある。
domains テーブルで変更されたラベルをマージする
本書の2番目のテーブルである wiki.domains は、各ドメインコードを言語に対応付ける。ディメンションテーブルが保持するのは件数ではなくラベルであり、マージは、いくつかのラベルが同時に変わる場合に適している。ここでの要点は、同じ形のステートメントがディメンションテーブルでも使えること、そして条件に関するルールがここでも当てはまることである。
UPDATE でもラベルを変更できるだろう。MERGE の形には WHEN NOT MATCHED 句もあり、テーブルにまだ存在しないドメインコードを挿入する。そのため、ドメインを追加するフィードにも同じステートメントを使える。このテーブルは DuckLake にのみ存在するので、マージも DuckLake 上で実行する。pageviews テーブルを DuckLake でマージする方法は、DuckLake での MERGEで扱う。パイプラインでは、ここでマージしたラベルが、第8章の結合が返すラベルになる。
1"""Merges one changed language label into the DuckLake copy of the domains table, then runs the same MERGE again. Read the second changed-row line against the sorted table, which shows the label that merged in."""23import pyarrow as pa45from lib.lakehouse import attach_ducklake, connect_ducklake, print_rows, read_domains, new_warehouse, safe_error67MERGE = """8MERGE INTO lake.wiki.domains AS t9USING labels AS s10ON t.domain_code = s.domain_code11WHEN MATCHED AND t.language <> s.language THEN UPDATE SET language = s.language12WHEN NOT MATCHED THEN INSERT (domain_code, language) VALUES (s.domain_code, s.language)13"""141516def main():17 with new_warehouse() as wh:18 lake = connect_ducklake(wh.con)19 attach_ducklake(lake, "lake", wh.root, inlining_row_limit=0) # inlining off, so the rows land in data files20 lake.execute("CREATE SCHEMA lake.wiki")21 lake.execute("CREATE TABLE lake.wiki.domains (domain_code VARCHAR, language VARCHAR)")22 lake.register("dims", read_domains())23 lake.execute("INSERT INTO lake.wiki.domains SELECT * FROM dims")2425 # 'fr' is already in the table, so this label is an update and not an insert26 lake.register("labels", pa.table({"domain_code": ["fr"], "language": ["French (France)"]}))27 print("rows changed by the merge:", lake.execute(MERGE).fetchall()[0][0])28 print("rows changed by the same merge again:", lake.execute(MERGE).fetchall()[0][0])29 print_rows(lake.execute("SELECT domain_code, language FROM lake.wiki.domains").fetchall()) # sorted, so the order DuckLake returns rows in does not matter303132if __name__ == "__main__":33 try:34 main()35 except Exception as exc: # the redacted error is what a reader sees36 print(safe_error(exc))37 raise SystemExit(1)
python merge-domains-label.pyrows changed by the merge: 1
rows changed by the same merge again: 0
de German
en English
fr French (France)
ja Japanese
fr のラベルを French から French (France) へ変更するマージ1回で、変更される行数は 1 である。同じマージをもう一度実行すると、変更される行数は 0 になる。テーブルは本書自身のデータにある4行から始まり、出力の末尾にあるソート済みのテーブルには、各ドメインとそのラベルが示される。
実践ルール: ディメンションテーブルも、ファクトテーブルと同じ WHEN MATCHED AND 条件でマージする。さらに、マージをもう一度実行して、何も変更されないことを確認する。ラベルの変更は、そのディメンションに結合するすべてのクエリに影響する。マージしようとするラベルを確認する。
本番で何がうまくいかなくなるか
訂正処理が実際に失敗する原因は、キーの重複、単一行の削除を繰り返すループ、そして履歴を読む人を戸惑わせるスナップショット数の三つである。いずれも書き込みの前に調べれば費用は小さいが、後から見つけると費用は大きい。したがって、これらの検査はバッチを書き込むジョブの中に置くべきである。
バッチ内のキーの重複。 訂正を二度送った場合や、不正な結合によって同じキーを持つ行が二つできた場合、そのバッチは無効になる。この例では、訂正した1行を二度送る。pyiceberg は何も書き込まないうちにこの upsert を拒否する。
1"""Sends a batch with one key twice to an Iceberg upsert and to a DuckLake MERGE, and prints each refusal with the row count after it. The two error lines carry the point: each names the cause of its refusal."""23import pyarrow as pa45from lib.lakehouse import KEY, hour_corrections, load_three_formats, new_warehouse, read_cut_hour, safe_error, scan_arrow67MERGE = """8MERGE INTO lake.wiki.pageviews_hourly AS t9USING batch AS s10ON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_title11WHEN MATCHED AND t.views <> s.views THEN UPDATE SET views = s.views12WHEN NOT MATCHED THEN INSERT (hour_utc, domain_code, page_title, views, response_bytes)13 VALUES (s.hour_utc, s.domain_code, s.page_title, s.views, s.response_bytes)14"""151617def main():18 with new_warehouse() as wh:19 iceberg, _, lake = load_three_formats(wh, range(6))20 corrected = hour_corrections(read_cut_hour(2))21 # A corrected row, sent twice: the batch holds two rows with one key.22 before = read_cut_hour(2)["views"].to_pylist() # the cut's views, to find the rows the correction changed23 changed = [i for i, after in enumerate(corrected["views"].to_pylist()) if after != before[i]]24 doubled = pa.concat_tables([corrected, corrected.slice(changed[0], 1)])2526 try:27 iceberg.upsert(doubled, join_cols=list(KEY))28 print("Iceberg upsert: no error")29 except Exception as exc:30 print("Iceberg upsert:", safe_error(exc, wh)) # safe_error replaces the warehouse path, so no local path is printed31 print("Iceberg rows after the failed upsert:", scan_arrow(iceberg).num_rows)3233 lake.register("batch", doubled)34 try:35 lake.execute(MERGE)36 print("DuckLake merge: no error")37 except Exception as exc:38 print("DuckLake merge:", safe_error(exc, wh))39 print("DuckLake rows after the failed merge:", lake.execute("SELECT count(*) FROM lake.wiki.pageviews_hourly").fetchall()[0][0])404142if __name__ == "__main__":43 try:44 main()45 except Exception as exc: # the redacted error is what a reader sees46 print(safe_error(exc))47 raise SystemExit(1)
python duplicate-source-keys.pyIceberg upsert: ValueError: Duplicate rows found in source dataset based on the key columns. No upsert executed
Iceberg rows after the failed upsert: 2999
DuckLake merge: InvalidInputException: Invalid Input Error: MERGE INTO command cannot affect the same target row more than once. A target row matched more than one source row; ensure the source rows are deduplicated or the ON condition is unique.
DuckLake rows after the failed merge: 2999
どちらの拒否でも、テーブルは書き込み前に持っていた行をすべて保っている。Iceberg の upsert は ValueError を送出し、テーブルには 2999 行が残っている。DuckLake の merge は InvalidInputException を送出し、その例外は原因として、ターゲットの1行が複数のソース行に一致したことを示している。テーブルには 2999 行が残っている。エラーを捕捉して同じバッチを再試行するパイプラインは、再び失敗する。問題はバッチ自体にあるからである。書き込みの前に、ソースをキーで重複排除する。キーが重複した場合の Delta Lake の merge は、ここでは検証していない(最初の節を参照)。
単一行の削除を繰り返すループ。 コピーオンライトでは、各削除が、その一致行を含むファイルを書き換えるコミットになる。ループで10回削除すると、一致行を含むファイルが10回書き換えられ、10個のスナップショットまたはバージョンが残る。これを示唆するのは、ここでの測定ではなくコストモデルである。削除する行を集め、それらを対象とする述語を指定して、削除を1回だけ書き込む。
読む人を戸惑わせるスナップショット数。 変更行と新規行を含む1回の upsert は、上の実行では 3 個のスナップショットを追加する。変更1件につき1コミットだと考えている読み手は、履歴が変更ログより長いことに気づく。スナップショットは期限切れにするまでテーブルのメタデータに残り、第7章でその方法を扱う。各スナップショットは、参照するファイルも保持し続ける。
どう気づくか。 これらはいずれも、すでに記録している数値に現れる。pyiceberg の結果に含まれる更新行数と挿入行数、および merge の変更行数は、送信したバッチと一致するはずである。再実行で変更が報告されるなら、バッチが想定と異なっている。スナップショット数が、1回のロードで想定される数(upsert では最大3)より速く増えるなら、append を二度送るような非冪等な再試行が疑われる。拒否は例外として現れるので、それを捕捉して処理を続けるジョブは、テーブルが更新されないままでも正常に見える。
実践ルール: 書き込みの前にバッチのキーの重複を検査し、拒否は一時的な障害ではなくバッチのバグとして扱う。削除は1回の書き込みにまとめる。訂正を監査するときは、スナップショットの一覧からスナップショット数を数える。
この章で下した判断
- 訂正は
hour_utc、domain_code、page_titleのキーで照合する。バッチは、書き込む前に各キーをちょうど1回だけ含んでいなければならない。 - 削除の例ではしきい値を180ビューとする。この絞り込みでは各時間で閲覧数の多い行だけが残るため、しきい値を2にすると該当する行がなくなるからである。
- Iceberg と Delta Lake の削除はコピーオンライトであり、それぞれの例では書き換えられるファイルを示す。DuckLake の
DELETEは削除ファイルを書き出し、データファイルはそのまま残す。同じ例でこの点も示す。 - 削除ベクトルは使わない。固定したバージョンでは deltalake 1.6.6 は削除ベクトルを書き出さず、この機能を有効にすると
to_pyarrow_tableとto_pyarrow_datasetはそのテーブルを受け付けなくなる。 - アップサートとマージは2回実行して確認する。2回目の実行では行が1つも変わらない。
- スナップショット数はスナップショットの一覧から読み取る。この章では、1回の呼び出しを1回のコミットとは見なさない。
- DuckLake の例ではインライン化をオフにする。理由は第1章で説明しており、これによりカウントはデータファイルの数を表す。
- 訂正はコードで組み立て、遅れて届く行は生成する。したがって、これらの例が示すのは書き込みの経路であり、実際の訂正の履歴ではない。
- キー重複の例では、拒否そのものを説明ではなく実際の出力として示す。そのため、失敗は読者の目に入る出力に現れる。
- この章には Delta Lake のアップサートやマージの例がないため、削除以外について deltalake のマージに関する主張はしない。
- 遅れて届く行と訂正は1つのバッチにまとめる。そのため、1回の呼び出しで更新と挿入の両方を示せる。
この版における本章
第2026.11.10版2026年11月20日時点で例が通過この章の5 例件のうち5件が合格
英語版の書籍(版2026.11.10)から翻訳した。