在資料表格式之間搬移,並檢查複本

閱讀約需 42 分鐘 分鐘,7 節 中共有 4 個範例。

版次 2026.11.10 範例於 2026年11 月 20 通過測試 39 個範例中有 39 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.10。 閱讀原文

讀完本章後,你將能把一張資料表從一種格式複製到另一種格式,並檢查複本是否保有相同的資料列。你也能指出複製後遺漏了哪些東西,並判斷哪些損失可以接受,哪些損失應該中止搬移。

分析師希望把 pageviews 資料表放進 DuckLake,透過 DuckDB 查詢目錄檔案。pageviews 資料表 wiki.pageviews_hourly 自第 1 章起就存放在 Apache Iceberg 中。另一個團隊的資料表存放在 Delta Lake,希望在 Iceberg 中取得相同的資料列。兩次搬移中,來源都留在原處,搬移的做法是複製到一張新資料表。複製只是一次性的寫入,大部分的工作都在它周圍的檢查。本章會完成這兩次複製,再加入能攔下無聲損失的檢查。

本章的範例固定使用 pyiceberg 0.12.0、deltalake 1.6.6,以及 duckdb 2.0.0,DuckLake 也由 DuckDB 執行。每個複製範例都會在暫存倉儲中,用同一份 pageviews 切片的三個小時資料建立自己的小型來源,共有 1499 列。

複製會保留與遺失什麼

最近一次變動於第 2026.11.10 版

複製是在某一個時間點讀取一個資料表的資料列,再以另一種格式寫入另一個資料表。每個目標函式庫都會寫入自己的資料檔、自己的中繼資料與自己的歷史紀錄。能夠通過這趟搬移而保留下來的,是雙方都能表示的內容:資料列,以及雙方都支援其型別的欄位。其餘的一切,不是留在來源端,就是必須在目標端以手動方式重新設定。

遺失的部分以表格呈現最為清楚。每一列列出資料表的一個部分、複製對它的處理,以及本章在何處展示結果。

資料表的部分 複製之後 本章展示的位置
資料列及其值 保留 摘要值檢查
欄位名稱與型別 在雙方格式都有該型別時保留 Delta Lake 一節
提交歷史 遺失。複製會另行開始一份自己的歷史 兩個複製的章節
分區規格 除非在目標端設定,否則遺失 DuckLake 一節
小於微秒的時間戳記 視格式而定:被拒絕、被截短或被保留 時間戳記一節

歷史紀錄是讀者常常沒有注意到的一項遺失。Iceberg 將變更記錄為快照,Delta Lake 則將每次提交記錄為一個版本。快照與時間旅行一章已說明讀取者如何使用它們。複製會在目標端開啟一份新的歷史,因此目標端的歷史從複製的那一刻才開始。只要你保留來源端,來源端就保有它自己的歷史。複製的結果中沒有任何內容指回那份歷史。

複製也不同於註冊。已註冊的中繼資料檔讓一個資料表在第二個目錄中可見,而不觸碰其檔案,因此兩個目錄讀取的是同一份資料。複製則會寫入新的檔案並且不動來源端,這表示現在有兩個資料表都接受寫入,彼此可能漸行漸遠。當目標端必須擁有自己的檔案與歷史時,選擇複製。當兩個目錄應當共用同一組檔案時,選擇註冊,並接受這些共用的檔案必須保持原位。

資料列之所以得以保留,是因為複製搬移的是值,而不是檔案。複製並不搬移資料檔。它從一個資料表讀出值,再為另一個資料表寫入新的 Parquet 檔案。這就是為什麼來源端與其副本的檔名和檔案數量會不同,也是為什麼比較檔名或檔案數量無法用來驗證複製結果。驗證必須比較資料列。

實用原則: 在複製之前,列出來源端擁有而目標端不會保留的項目:它的歷史、它的分區規格,以及任何比目標端所能儲存的精度更細的值。為每個項目各做一項決定:接受該項遺失、在目標端以手動方式設定該屬性,或是中止搬移。執行手冊應當寫明每一項決定。

將 pageviews 資料表複製到 DuckLake

最近一次變動於第 2026.11.10 版

複製的做法是先以 scan_arrow 讀取 Iceberg 資料表,再把這些資料列交給 DuckLake。DuckLake 會依這些資料列的欄位建立一張空資料表,替它設定分區規格,然後以 INSERT ... SELECT 寫入資料列。以 Arrow 作為橋梁,是因為雙方各自沿用自己的函式庫:pyiceberg 讀取來源,DuckDB 則透過自己的 ducklake 擴充功能寫入 DuckLake 資料表。任何一方都不讀取對方的檔案。目錄章已說明如何掛接 DuckLake 目錄,本章的輔助函式以相同的方式掛接。

來源資料表依 hour_utc 的小時分區,這正是由每日分區改為每小時分區一節最後得到的配置。這裡由 pyiceberg 以每小時的規格建立該來源,接著追加三個小時的資料,每次追加各為一次提交:

iceberg-to-ducklake-copy.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通過
"""Copy an Iceberg table into DuckLake through Arrow, then print what the copy kept of the layout and the history.The point rests on the copy partition transforms and copy files per partition lines, which show whether thelayout arrived with the rows, and on the copy snapshot lines, which show the history starting at the copy."""from pyiceberg.partitioning import PartitionField, PartitionSpecfrom pyiceberg.transforms import HourTransformfrom lib.lakehouse import (copy_to_ducklake, create_iceberg_table, ducklake_files_by_partition, ducklake_partition_transforms,                           new_warehouse, read_cut_hour, safe_error, scan_arrow, TABLE)def main():    try:        with new_warehouse() as wh:            # source_id 1 is the field ID of hour_utc in the table lib creates            spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=HourTransform(), name="ts_hour"))            table = create_iceberg_table(wh, partition_spec=spec)            for hour in range(3):                table.append(read_cut_hour(hour))            arrow = scan_arrow(table)            print(f"source rows: {arrow.num_rows}")            print(f"source snapshots: {len(table.metadata.snapshots)}")            for field in table.spec().fields:                print(f"source partition field: {field.name}")            # the helper creates the copy empty, sets this spec with ALTER, and only then inserts the rows            target = copy_to_ducklake(wh, arrow, partition_by="hour(hour_utc)")            print(f"copy rows: {wh.con.execute(f'SELECT count(*) FROM {target}').fetchall()[0][0]}")            # current=True keeps only the spec still in force; an earlier spec would otherwise be listed too            print(f"copy partition transforms: {ducklake_partition_transforms(wh.con, table=TABLE, current=True)}")            # one (partition value, files, rows) tuple per partition, in value order            files = ducklake_files_by_partition(wh.con, "lake", TABLE)            print(f"copy partition values: {[value for value, _, _ in files]}")            print(f"copy files per partition: {[count for _, count, _ in files]}")            print(f"copy rows per partition: {[int(rows) for _, _, rows in files]}")            changes = wh.con.execute("SELECT changes FROM ducklake_snapshots('lake') ORDER BY snapshot_id").fetchall()            # labels start at 1, so label N is the snapshot whose snapshot_id is N-1            for number, (change,) in enumerate(changes, start=1):                print(f"copy snapshot {number}: {', '.join(sorted(change))}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
輸出python iceberg-to-ducklake-copy.py
source rows: 1499
source snapshots: 3
source partition field: ts_hour
copy rows: 1499
copy partition transforms: ['hour']
copy partition values: ['0', '1', '2']
copy files per partition: [1, 1, 1]
copy rows per partition: [499, 500, 500]
copy snapshot 1: schemas_created
copy snapshot 2: schemas_created
copy snapshot 3: tables_created
copy snapshot 4: tables_altered
copy snapshot 5: tables_inserted_into

輔助函式 scan_arrow 以來源目前的快照讀取資料,並把該快照的所有資料列以單一 Arrow 資料表傳回。因此複製所得的是某一時刻的資料列,也就是掃描所見的最後一次提交。掃描之後才提交的寫入不在複製結果內,而複製結果本身也不會告訴你這一點。在複製掃描之後才送達、卻始終沒有進入複製結果的提交,就是切換(cutover)問題,生產環境一節會再回頭討論。

決定複製是否成功的有兩個問題:資料列與配置是否都已到位,以及隨之而來的歷史有哪些?輸出可以回答這兩者。

先看來源。它印出資料列數、快照數與分區欄位。來源有 3 個快照,每次追加各一個;分區欄位只有一個,即 ts_hour,是 hour_utc 的小時轉換。

接著是複製後的資料列數,為 1499,與來源相同。這是有用的初步檢查,但為何光靠它並不足夠,後面的摘要值(digest)一節會說明。

複製可能在沒有任何錯誤的情況下遺失配置,所以敘述的順序很重要。輔助函式先把複製目標建立為空資料表,對它執行 ALTER TABLE ... SET PARTITIONED BY (hour(hour_utc)),之後才寫入資料列。DuckLake 分區文件指出,分區鍵「只影響寫入資料表的新資料」,因此若在資料列已就位之後才執行 ALTER,這些資料列將維持未分區的狀態。輔助函式只保留仍然有效的規格,並列出一個轉換 hour。這份清單說明複製目標被賦予了什麼,而檔案則說明它實際持有什麼:複製寫出 [1, 1, 1] 個檔案,資料列在這些檔案之間的分配為 [499, 500, 500]。若以單一敘述完成複製,目標不帶任何分區規格,清單就是空的,資料列也位於未分區的檔案中。無論哪種做法,資料列都全數在場,所以檢查必須看配置。

分區清單讀取的是目錄資料表 ducklake_partition_column,其定義見 DuckLake 規格,讀取方式是透過已掛接的中繼資料資料庫。在這個固定版本中,沒有公開函式可以傳回它。

最後,快照清單顯示複製目標的歷史。每一行列出快照的編號及其所做的變更。這些標籤計入 DuckLake 記錄的每一個快照,包括初始設定,做法與第 2 章相同。前兩個快照建立預設結構描述與 wiki 結構描述;第三個建立空資料表,第四個設定其分區規格,第五個把資料列寫入已完成分區的資料表。來源的三次每小時追加並未出現。複製目標的歷史從它自己的建立時刻起算,因此對複製目標做時間旅行,只能回溯到那一刻。若要讀取來源在第一個小時之後的樣貌,仍然需要 Iceberg 資料表。

掛接輔助函式也把 DATA_INLINING_ROW_LIMIT 設為 0,因此複製的資料列會寫成 Parquet 檔案,上述的檔案數即是這些檔案的計數。

**實用原則:**透過 Arrow,並以目標端自己的寫入器進行複製。先把目標建立為空資料表,以 ALTER 設定其分區規格,之後才寫入資料列。印出目標的分區清單與每個分區的檔案數。把複製目標的快照視為它自己的歷史,並保留來源,直到最後兩節的檢查全部通過為止。

將 Delta 資料表複製到 pyiceberg 資料表

最近一次變動於第 2026.11.7 版

Delta 來源的建立方式,就如同團隊的資料管線會採用的做法:以 deltalake 進行三次附加(append),每小時一次。這三次附加分別是版本 0、1 和 2。複製時以 read_delta 讀取目前的資料列,再將它們附加到依目標綱要(schema)建立的 Iceberg 資料表:

delta-to-iceberg-copy.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通過
"""Copy a Delta Lake table into Iceberg through Arrow, then compare the copy with its source.The point rests on the delta versions and iceberg snapshots lines, which show several commits becoming one,and on the two column listings, which show the names carried across."""from deltalake import DeltaTablefrom lib.lakehouse import (create_iceberg_table, new_warehouse, print_schema, read_delta, safe_error, scan_arrow,                           write_delta_hours)def main():    try:        with new_warehouse() as wh:            path = write_delta_hours(wh.root, range(3))            source = read_delta(path)            # Delta numbers its versions from 0, so the count is the last version plus one            print(f"delta versions: {DeltaTable(path).version() + 1}")            print(f"delta rows: {source.num_rows}")            print("delta columns (name, type, nullability):")            print_schema(source.schema)            table = create_iceberg_table(wh)            table.append(source)            print(f"iceberg snapshots: {len(table.metadata.snapshots)}")            print(f"iceberg rows: {scan_arrow(table).num_rows}")            print("iceberg columns (name, type, requirement):")            # sorted by name, so the two listings line up row for row            for field in sorted(table.schema().fields, key=lambda field: field.name):                # Iceberg calls a nullable field optional, so the listing says optional where Delta says nullable                requirement = "required" if field.required else "optional"                print(f"{field.name}\t{field.field_type}\t{requirement}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
輸出python delta-to-iceberg-copy.py
delta versions: 3
delta rows: 1499
delta columns (name, type, nullability):
domain_code	string	nullable
hour_utc	timestamp[us]	nullable
page_title	string	nullable
response_bytes	int64	nullable
views	int64	nullable
iceberg snapshots: 1
iceberg rows: 1499
iceberg columns (name, type, requirement):
domain_code	string	optional
hour_utc	timestamp	optional
page_title	string	optional
response_bytes	long	optional
views	long	optional

複製後的資料列數與來源相同,但歷史紀錄不會保留。Delta 資料表有 3 個版本與 1499 列資料。Iceberg 資料表是以一次附加寫入全部資料而建立,因此它有 1 個快照,這是它自身歷史的起點,與 DuckLake 的複製結果相同。它的資料列數 1499 與來源一致。

輸出的其餘部分會逐行列出兩邊的綱要,每行一個欄位。請並排對照:

欄位 Delta Lake(Arrow 型別) Iceberg 型別
domain_code string string
hour_utc timestamp[us] timestamp
page_title string string
response_bytes int64 long
views int64 long

名稱原封不動地帶過來,因為複製時是從 Arrow 綱要取得名稱。型別則是一對一對應。唯一的寫法差異是 Arrow 的 int64,Iceberg 稱之為 long。兩邊的 hour_utc 都使用微秒,下方的時間戳記檢查會說明兩者不一致時會發生什麼事。

pyiceberg 對名稱的要求很嚴格。它在寫入前,會先檢查 Arrow 綱要與資料表的綱要是否相符。若欄位名稱不同,或型別無法提升(promote)為資料表的型別,它會以不相符的錯誤停止。對於可以提升的型別,例如 int 到 long,它則會接受。這項檢查位於所固定版本之函式庫的 _check_pyarrow_schema_compatible 函式中,檔案為 pyiceberg/io/pyarrow.py。在這個固定版本下,Delta 資料表也無法重新命名欄位,如綱要章中重新命名一節所示。若兩邊的名稱不一致,要修改的是目標,而不是來源。pyiceberg 以名稱將 Arrow 欄位對應到資料表,因此目標的欄位 ID 來自您所撰寫的綱要。您要自行撰寫目標綱要,而不是讓第一個批次來決定它。

**實用原則:**自行撰寫目標綱要,使用您想要的型別,並在複製後印出兩邊的綱要,如範例所示。只有在輸出中確認過之後,才接受 int64 到 long 這類近似相等的型別。名稱不同則不可接受。

複製前先檢查時間戳記精度

最近一次變動於第 2026.11.7 版

時間戳記是各種格式彼此不一致的地方,而且有時不會有任何提示。Iceberg 規格將奈秒時間戳記定義為第 3 版的型別,因此第 2 版的資料表沒有對應的型別(Iceberg 規格,第 3 版一節)。本範例的資料表是第 2 版,也就是預設版本。在這個固定版本下,pyiceberg 拒絕寫入第 3 版,所以奈秒值只能由 Iceberg 以外的格式保存。本範例將兩個僅在微秒以下有差異的值,1000000500 與 1000000999 奈秒,分別寫入每一種格式:

timestamp-precision-check.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通過
"""Write two timestamps that differ only below a microsecond to Iceberg, Delta Lake and DuckLake, and show what each kept.The point rests on the Iceberg error line and on the Delta and DuckLake read-back lines."""import pyarrow as pafrom deltalake import write_deltalakefrom pyiceberg.schema import Schemafrom pyiceberg.types import NestedField, TimestampTypefrom lib.lakehouse import copy_to_ducklake, new_warehouse, NAMESPACE, read_delta, safe_error, sql_rows# nanoseconds since 1970: one second plus 500 and 999 nanoseconds, so the two values differ below a microsecondNANOSECONDS = pa.table({"hour_utc": pa.array([1000000500, 1000000999], pa.timestamp("ns"))})def main():    try:        with new_warehouse() as wh:            # cast to int64 gives the integer behind each timestamp, so distinct values are counted exactly            print(f"written distinct values: {len(set(NANOSECONDS['hour_utc'].cast(pa.int64()).to_pylist()))}")            # TimestampType stores microseconds; a version 2 table has no nanosecond type to declare instead            table = wh.catalog.create_table(                f"{NAMESPACE}.precision",                schema=Schema(NestedField(1, "hour_utc", TimestampType(), required=False)),            )            try:                # this append raises, because the table cannot hold nanoseconds; the except prints the error                table.append(NANOSECONDS)            except Exception as exc:                print(f"iceberg append: {safe_error(exc, wh)}")            path = str(wh.root / "precision")            write_deltalake(path, NANOSECONDS, mode="overwrite")            # the cast reads the count in the column's unit, which Delta wrote as microseconds, so 1000000 is one second            kept = read_delta(path)["hour_utc"].cast(pa.int64()).to_pylist()            print(f"delta read back as microseconds: {kept}")            print(f"delta distinct values read back: {len(set(kept))}")            target = copy_to_ducklake(wh, NANOSECONDS)            # epoch_ns returns nanoseconds since 1970, so a value cut to microseconds would end in three zeros            rows = sql_rows(wh.con, f"SELECT epoch_ns(hour_utc) FROM {target}")            print(f"ducklake epoch nanoseconds read back: {[row[0] for row in rows]}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
輸出python timestamp-precision-check.py
written distinct values: 2
iceberg append: UnsupportedPyArrowTypeException: Column 'hour_utc' has an unsupported type: timestamp[ns]
delta read back as microseconds: [1000000, 1000000]
delta distinct values read back: 1
ducklake epoch nanoseconds read back: [1000000500, 1000000999]

第一行是輸入,即兩個相異的值。接著各格式以自己的方式回應。

Iceberg 的附加寫入失敗,錯誤為 UnsupportedPyArrowTypeException: Column 'hour_utc' has an unsupported type: timestamp[ns]。錯誤訊息指出了欄位與型別,因此這是三種情況中最清楚的失敗,而且預設不會有任何內容被悄悄更動。pyiceberg 的錯誤訊息指出一項設定 PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE,它會在寫入時將奈秒降為微秒。啟用該設定後,同樣的附加寫入會成功,讀回的值是整數微秒,只留下一則記錄的警告。這與 Delta 所做的截斷相同,因此只應在已決定截斷數值的工作中設定它,不要設在所有寫入者共用的環境中。

Delta 的寫入成功,讀回的結果顯示 [1000000, 1000000]。兩個值都被截斷為整數微秒,兩個相異的值變成了一個。寫入沒有引發任何錯誤,列數也相同。只有檢查數值才能發現損失。相異值的數量從 2 降為 1。

DuckLake 保留了奈秒。它的資料表依寫入時的樣子儲存這兩個值,範例讀回的結果為 [1000000500, 1000000999]。

pageviews 資料表記錄的是小時,因此這種情況不會碰到問題。原始請求記錄的資料表則會。它的時間戳記來自計時比微秒更細的時鐘,複製時必須為那些位數選定規則。請在第一次複製之前,對每個時間戳記欄位提出這個問題,因為答案只有在數值中才看得出來。本章的複製使用微秒時間戳記,三種格式都能保存,所以複製結果一致。真實的資料表可能含有來源端微秒以下的值,複製必須在第一次寫入之前決定如何處理它們。

實用原則: 在第一次複製之前,用一個微秒以下的值檢查時間戳記精度。事先選定規則:將欄位轉換為微秒並計算轉換更動的值的數量、拒絕該次複製,或寫入能保存奈秒的格式。不要把選擇交給寫入器函式庫,因為悄悄的截斷不會產生可供處理的錯誤。

用排序後的摘要檢查每一份副本

最近一次變動於第 2026.11.10 版

列數相符,並不能證明各列的值也相符。副本可能保留了列數,卻改動了某個值,而列數看不出這件事;摘要則看得出來。資料表的摘要是其排序後各列的雜湊值:digest_rows 先將各列排序,把每一列寫成一行文字,再對結果進行雜湊。排序使摘要與各列傳回的順序無關,因此兩份列內容相同的副本會得到相同的摘要,無論各格式以何種順序傳回。digest_rows 會在兩份副本上執行,也會在一份刻意改動了一個瀏覽次數的副本上執行:

verify-copies-by-digest.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 通過
"""Check each copy against its source with a sorted digest, and show that one changed value fails it.The point rests on the two iceberg to ducklake digest lines: the copy matches its source, and a copy with onechanged count does not."""from lib.lakehouse import (copy_to_ducklake, create_iceberg_table, digest_rows, new_warehouse, read_cut_hour,                           read_delta, safe_error, scan_arrow, sql_rows, write_delta_hours)def same(source, copy):    return digest_rows(source) == digest_rows(copy)def check_iceberg_to_ducklake():    with new_warehouse() as wh:        table = create_iceberg_table(wh)        for hour in range(3):            table.append(read_cut_hour(hour))        target = copy_to_ducklake(wh, scan_arrow(table))        source_rows = sql_rows(wh.con, "SELECT * FROM source", source=scan_arrow(table))        copy_rows = wh.con.execute(f"SELECT * FROM {target}").fetchall()        first = copy_rows[0]        # the copy's columns are hour_utc, domain_code, page_title, views, response_bytes, so index 3 is views        changed = [(*first[:3], first[3] + 1, first[4]), *copy_rows[1:]]        print(f"iceberg to ducklake rows: {len(source_rows)} and {len(copy_rows)}")        matches = same(source_rows, copy_rows)        # printed before the assert, so a failing run still shows the word        print(f"iceberg to ducklake digests: {'match' if matches else 'differ'}")        assert matches        still_matches = same(source_rows, changed)        print(f"iceberg to ducklake with one changed view count digests: {'match' if still_matches else 'differ'}")        # one changed count must change the digest        assert not still_matchesdef check_delta_to_iceberg():    with new_warehouse() as wh:        path = write_delta_hours(wh.root, range(3))        table = create_iceberg_table(wh)        table.append(read_delta(path))        source_rows = sql_rows(wh.con, "SELECT * FROM source", source=read_delta(path))        copy_rows = sql_rows(wh.con, "SELECT * FROM copy", copy=scan_arrow(table))        print(f"delta to iceberg rows: {len(source_rows)} and {len(copy_rows)}")        assert same(source_rows, copy_rows)def main():    try:        check_iceberg_to_ducklake()        check_delta_to_iceberg()    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
輸出python verify-copies-by-digest.py
iceberg to ducklake rows: 1499 and 1499
iceberg to ducklake digests: match
iceberg to ducklake with one changed view count digests: differ
delta to iceberg rows: 1499 and 1499

只要改動一個數字,摘要就會改變,所以摘要相符是一項證據,摘要不同則必須停下。以 Iceberg 到 DuckLake 的副本 為例,輸出會印出兩個列數,兩者相等,接著是摘要 match。對 Delta 到 Iceberg 的副本進行同樣的檢查,結果也相符。當一個瀏覽次數被改動後,摘要 differ。

摘要比對的是資料庫傳回的值,而且有其限制。若在雜湊之前將兩端都轉成文字,不同型別的兩個值可能產生相同的文字。整數 1 與文字 '1' 就是相同的文字。因此應如本範例所做,比較具型別的值,並像 Delta 到 Iceberg 的副本 那樣印出結構描述。摘要也完全不涉及欄位名稱或型別:兩張資料表若列內容相同而欄位名稱不同,摘要也會相同。前面各節的結構描述清單檢查名稱,摘要檢查值,所以一份副本兩者都需要。

摘要並不是檔案的雜湊。各列依其具型別的值排序,每一列成為一行其 Python 表示形式的文字,串接後的文字再以 SHA-256 進行雜湊。值相等的兩列會產生相等的行,這正是比對所需要的。一個值的改變會改變一行,進而改變整個摘要。

此外也要選定檢查的時機。摘要只對執行當下存在的列成立。在那之後對來源的任何寫入,都會使副本過時,先前計算的摘要也不再適用。檢查應安排在來源的最後一次寫入之後,且在任何人讀取副本之前。

實用原則: 在來源的最後一次寫入之後,對兩端使用相同的欄位與具型別的值計算摘要。列數與摘要要一併比對。在兩者都相符之前,不要切換讀取端,也不要刪除來源。若複製期間仍有寫入者在執行,請重新複製並重新計算摘要。

此部分尚未翻譯,因此以英文呈現。

What goes wrong in production

最近一次變動於第 2026.11.7 版

A failed migration usually passes the first check and fails later. These are the failures to look for, and how you would notice each.

  • A cutover that races a writer. A digest covers only the rows it read, as the digest section says. The first append after it makes the copy stale, and the digest does not warn you. Stop the writers, copy, digest and then move the readers. If the writers cannot stop, copy in windows and check the rows that arrived after the last window.
  • Deleting the source before the checks pass. The source holds the history that the copy does not. Once the source is gone, time travel into its snapshots and versions goes with it. Keep the source until the digests match and every reader has moved. Then decide how long to keep it, in writing.
  • A copy with the rows and without the layout. A copy made without the ALTER would hold every row and match the digest, with no partition set. The partition list and the files per partition are the checks that show the layout is missing, so print both after the copy.
  • Timestamps that change without an error. Delta Lake cut the nanosecond values to microseconds and raised no error. The row count stayed the same. A check on the values is the only thing that catches it, so a copy with sub-microsecond data needs that check before it runs.
  • Names and types that differ. pyiceberg refuses an append whose column names differ from the table's, or whose type it cannot promote, and that refusal is the clearest failure. The harder case is a column whose name matches and whose type it accepts, such as a long that was an int. Print both schemas and read them, rather than trusting that the append succeeded.
  • Size and memory. The helpers in this chapter read a whole table into memory before they write it. That suits 1499 rows. A table of billions of rows needs a copy that reads and writes in batches, and the digest must then be computed over the same batches on both sides, so it stays a check of the whole table.
  • Readers that write to both tables. During a copy, a job that writes to both tables by mistake makes the two tables differ, and the digest will show a mismatch that no single write explains. Name one writer per table in the runbook before the cutover starts.
  • A digest over text. A digest over casts can match when the types differ. The check in this chapter compares typed values, and the runbook should say so, so that a later edit to the check does not quietly drop the types.

此部分尚未翻譯,因此以英文呈現。

Decisions this chapter made

最近一次變動於第 2026.11.7 版
  • Copies go through Arrow, and each target is written by the library that owns its format. pyiceberg writes Iceberg, DuckDB's ducklake extension writes DuckLake, and deltalake writes Delta Lake. This book does not use DuckDB's iceberg or delta extensions, so no copy in it depends on them.
  • Delta tables are read through read_delta, for the reason in chapter 8. Every Delta read in this chapter goes through it.
  • A copy is one-time, starts a new history and is checked before anyone switches to it. The source stays in place until the digests match and the readers have moved.
  • The partition spec is set on the target by hand, with an ALTER before the rows are inserted, and printed. The copy does not bring it across.
  • Each copy example builds its own source from the same three hours of the cut. Every example runs alone, and each check reads only the rows that its own example wrote.
  • Checks run on typed values, after the last write, over the same columns. The row count and the digest are read together, and neither one is used alone to call a copy good.
  • The copies use microsecond timestamps, and a separate example checks sub-microsecond values. Each copy in this chapter keeps its microsecond values, so the digests match. The precision example shows what each format does with a value it cannot keep.
  • Metadata-only migration is not used here. pyiceberg's Table.add_files adds Parquet files that already exist to an Iceberg table as data files (Table.add_files in pyiceberg/table/__init__.py, pyiceberg 0.12.0). Its API docs, which are not pinned to that version, describe this as committing the files without rewriting them. That keeps the data files in place, which a copy does not. This chapter did not run it, and it copies rows instead.

本章,於本版次中

版次 2026.11.10範例於 2026年11 月 20 通過測試本章 4 個範例 個範例中有 4 個通過

譯自英文書,版次 2026.11.10。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 9 章,共 10 章: 在資料表格式之間搬移,並檢查複本

  1. 複製會保留與遺失什麼
  2. 將 pageviews 資料表複製到 DuckLake
  3. 將 Delta 資料表複製到 pyiceberg 資料表
  4. 複製前先檢查時間戳記精度
  5. 用排序後的摘要檢查每一份副本
  6. What goes wrong in production
  7. Decisions this chapter made

返回頂端所有章節