삭제, 갱신, 병합으로 행 바로잡기

읽는 데 약 29분분 걸린다, 9절에 5개 예제이(가) 있음.

2026.11.10판 예제 통과 2026년 11월 20 39개 예제 중 39개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.10판을 번역한 것이다. 원문 읽기

이미 커밋된 행도 바꿀 수 있다. 이 장에서는 Iceberg, Delta Lake, DuckLake에서 행을 삭제하고, upsert하고, 병합한다. 각 쓰기 작업이 파일에 어떤 영향을 주는지 설명하고, pyiceberg upsert가 추가하는 스냅샷의 수를 센다.

지금까지 테이블은 늘어나기만 했다. 1장의 모든 쓰기는 wiki.pageviews_hourly에 행을 추가했으며, 이 테이블에는 원천 시스템이 한 시간 분량을 가끔 다시 전달하기도 한다.

늦게 도착한 데이터는 정정으로 들어온다

마지막으로 변경된 판: 2026.11.10판

1장의 테이블에는 02시 데이터의 첫 번째 전달분이 그 시점에 소스가 보낸 집계값 그대로 들어갔다. 같은 시간대의 이후 전달분에는 일부 페이지의 정정된 집계값이 담겨 있으며, 첫 번째 전달분이 빠뜨린 페이지도 하나 있다. 정정에 포함된 페이지는 이전과 같은 페이지이므로, 테이블은 행을 제자리에서 바꿔야 한다. 정정된 시간대를 그대로 추가하면 모든 페이지가 집계값별로 한 번씩, 즉 두 번 저장된다.

이 책에서 행은 키로 식별된다. 키는 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

마지막으로 변경된 판: 2026.11.7판

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.

delete-low-views.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""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."""from datetime import datetimefrom deltalake import DeltaTablefrom pyiceberg.expressions import And, EqualTo, LessThanfrom lib.lakehouse import DUCKLAKE_ALIAS, NAMESPACE, TABLE, ducklake_file_count, load_three_formats, new_warehouse, read_delta, safe_error, scan_arrowHOUR_02 = datetime(2024, 6, 3, 2)# 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.LOW_VIEWS = 180def main():    with new_warehouse() as wh:        iceberg, delta_path, lake = load_three_formats(wh, range(6))  # hours 00 to 05, one commit per hour in each format        iceberg_before = scan_arrow(iceberg).num_rows        delta_before = read_delta(delta_path).num_rows        table = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"        lake_before = lake.execute(f"SELECT count(*) FROM {table}").fetchall()[0][0]        files_before = ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE)  # counted before the delete, to compare with the count after        iceberg.delete(And(EqualTo("hour_utc", HOUR_02), LessThan("views", LOW_VIEWS)))        summary = iceberg.current_snapshot().summary  # the snapshot summary counts each data file the delete removed from the table        print("Iceberg deleted rows:", iceberg_before - scan_arrow(iceberg).num_rows)        print("Iceberg remaining rows:", scan_arrow(iceberg).num_rows)        print("Iceberg data files rewritten:", summary["deleted-data-files"])        delta = DeltaTable(delta_path)        # the hour is written as a timestamp string inside the SQL predicate        metrics = delta.delete(f"hour_utc = '2024-06-03T02:00:00' AND views < {LOW_VIEWS}")        print("Delta Lake deleted rows:", delta_before - read_delta(delta_path).num_rows)        print("Delta Lake remaining rows:", read_delta(delta_path).num_rows)        print("Delta Lake data files rewritten:", metrics["num_removed_files"])        lake.execute(f"DELETE FROM {table} WHERE hour_utc = TIMESTAMP '2024-06-03 02:00:00' AND views < {LOW_VIEWS}")        lake_after = lake.execute(f"SELECT count(*) FROM {table}").fetchall()[0][0]        print("DuckLake deleted rows:", lake_before - lake_after)        print("DuckLake remaining rows:", lake_after)        print("DuckLake data files before:", files_before)        print("DuckLake data files after:", ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE))        # a delete file is listed against the data file it applies to, so counting the listed rows that have one counts the delete files        print("DuckLake delete files written:", lake.execute(            f"SELECT count(*) FROM ducklake_list_files('{DUCKLAKE_ALIAS}', '{TABLE}', schema => '{NAMESPACE}') "            "WHERE delete_file IS NOT NULL").fetchall()[0][0])if __name__ == "__main__":    try:        main()    except Exception as exc:  # the redacted error is what a reader sees        print(safe_error(exc))        raise SystemExit(1)
출력python delete-low-views.py
Iceberg 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)는 삭제된 행의 위치만 기록하므로 쓰기가 싸다. 대신 데이터 파일을 다시 쓰기 전까지 그 비용이 읽기로 넘어간다.

이 장에서 다루는 세 가지 형식은 다음과 같이 다르다.

형식 고정 버전의 라이브러리 고정 버전에서 라이브러리가 삭제를 쓰는 방식 이 장에서 보이는 곳
Iceberg pyiceberg 0.12.0 카피 온 라이트. delete는 조건에 맞는 행이 들어 있는 데이터 파일을 다시 쓰며 삭제 파일은 쓰지 않는다. write.delete.mode를 머지 온 리드로 설정하면 pyiceberg는 "Merge on read is not yet supported, falling back to copy-on-write"라는 경고를 낸다(출처). 예, 삭제 예제에서
Delta Lake deltalake 1.6.6 카피 온 라이트. 조건에 맞는 행이 있는 파일을 다시 쓰고, 로그에는 이전 파일이 제거된 것으로 기록한다. 예, 삭제 예제에서
DuckLake DuckDB 2.0.0 머지 온 리드. DELETE는 삭제 파일을 쓰고 데이터 파일은 그대로 둔다. 예, 삭제 예제에서

DuckLake 행은 삭제 예제에서 확인한다. 이 예제는 삭제 파일과 그대로 남아 있는 데이터 파일의 수를 센다. 삭제 벡터에 관한 DuckLake 문서는 삭제된 행의 위치를 .puffin 파일에 기록하는 실험적 옵션을 설명한다. 이 옵션은 기본값이 꺼짐이며, 이 장에서는 켜지 않는다. 삭제 파일을 거쳐 읽는 비용은 여기서 측정하지 않는다. 머지 온 리드 테이블을 읽는 쪽은 데이터 파일을 다시 쓰기 전까지 매번 스캔할 때마다 이 비용을 치르므로, 독자 자신의 테이블에서 측정해야 한다.

Delta Lake에도 삭제된 행의 위치를 파일에 기록하는 삭제 벡터가 있다. 이는 세 번째 쓰기 방식이 아니라 Delta의 머지 온 리드 옵션이며, 이 책에서는 사용하지 않는다. 고정 버전에서 deltalake 1.6.6는 삭제 벡터를 쓰지 않는다. 이 기능을 활성화한 테이블에서도 delete는 여전히 파일을 다시 쓴다. Delta 프로토콜은 테이블이 삭제 벡터를 사용하면 테이블의 리더 기능과 라이터 기능에 삭제 벡터 기능을 요구하며, 이 기능을 활성화하면 양쪽에 모두 추가된다. 이 책에서 모든 Delta 읽기에 쓰는 QueryBuilder는 이런 테이블을 읽을 수 있다. to_pyarrow_table와 to_pyarrow_dataset는 테이블이 그 기능을 선언했다는 이유로 이런 테이블을 거부한다. 그래서 이 책은 이 기능을 꺼 두며, 이 책의 Delta 삭제는 카피 온 라이트이다.

작업 규칙: 카피 온 라이트 삭제는 일치하는 행이 든 파일마다 그 파일을 다시 쓰는 비용이 든다고 예상한다. 일치하는 행이 적은 수의 파일에 모여 있는 조건, 예를 들어 한 시간 단위 조건을 선호하고, 이미 알고 있는 삭제는 모아서 한 번의 쓰기로 처리한다. 머지 온 리드는 쓰기가 잦고, 데이터 파일을 다시 쓰기 전까지 읽기가 삭제 파일의 비용을 감당할 수 있는 테이블에 알맞다.

수정된 시간대 upsert

마지막으로 변경된 판: 2026.11.10판

upsert는 키가 일치하는 행은 갱신하고, 키가 일치하지 않는 행은 삽입한다. 수정된 시간대에는 테이블에 이미 있는 키가 들어 있고, 늦게 도착한 행에는 테이블에 아직 없는 키가 들어 있으므로, 정정에는 이 쓰기 방식이 알맞다. 단순 append는 수정된 행을 원본 옆에 그대로 저장하므로, 그 시간대의 모든 페이지가 두 번씩 나타난다.

다음 두 하위 절에서는 같은 배치를 가지고 pyiceberg의 메서드와 DuckLake의 SQL MERGE를 보인다.

키는 변경이 적용될 행을 찾아 주고, 들어오는 두 행이 같은 행인지도 결정한다. 키가 너무 좁으면 실제로 다른 두 행이 하나로 합쳐지고, 키가 너무 넓으면 사본이 하나 더 삽입된다. 여기서 키는 hour_utc, domain_code, page_title이며, 1장에서 데이터를 잘라 낼 때 각 행에 부여한 식별 단위이다. 예제의 배치에는 각 키가 한 번씩만 들어 있다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Upserts in pyiceberg

마지막으로 변경된 판: 2026.11.7판

pyiceberg's upsert takes an Arrow table of rows and the columns that form the key, passed as join_cols. It returns the count of rows it updated and the count it inserted. A row counts as updated only when a non-key column changed, so a row that is identical to the table is not counted as updated. Copy-on-write still rewrites such a row when its file also holds a changed row.

Send the corrected hour and the late row through one upsert, and count what the call leaves in the table's history.

redeliver-hour-upsert.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""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."""import pyarrow as pafrom lib.lakehouse import KEY, hour_corrections, load_three_formats, new_warehouse, read_cut_hour, safe_error, snapshot_labelsdef main():    with new_warehouse() as wh:        iceberg, _, _ = load_three_formats(wh, range(6))        before = {snapshot.snapshot_id for snapshot in iceberg.snapshots()}  # so the loop below lists only the snapshots this upsert adds        # hour_corrections halves the views of the first 20 page titles in byte order, so the same titles change on every run        corrected = hour_corrections(read_cut_hour(2))        # A late row: a page the first delivery of hour 02 did not have.        late = corrected.slice(0, 1).set_column(            corrected.schema.get_field_index("page_title"),            "page_title",            pa.array(["Late_arrival_example"], type=pa.string()),        )        batch = pa.concat_tables([corrected, late])        result = iceberg.upsert(batch, join_cols=list(KEY))  # KEY is the three key columns; a row matches when all three are equal        # rows_updated counts only rows whose non-key values changed, so identical rows are not counted        print("rows updated:", result.rows_updated)        print("rows inserted:", result.rows_inserted)        iceberg.refresh()        labels = snapshot_labels([snapshot.snapshot_id for snapshot in iceberg.snapshots()])  # snapshot IDs change on every run, so the labels number commits        added = [snapshot for snapshot in iceberg.snapshots() if snapshot.snapshot_id not in before]        for snapshot in added:            label = labels[snapshot.snapshot_id]            print(label, snapshot.summary.operation.value)            # a snapshot that adds or deletes no records has no such key, so the count is 0            print(f"{label} records added:", snapshot.summary.get("added-records") or 0)            print(f"{label} records deleted:", snapshot.summary.get("deleted-records") or 0)        print("snapshots added:", len(added))        again = iceberg.upsert(batch, join_cols=list(KEY))  # the same batch again, as a retry would send it        print("rows updated on second upsert:", again.rows_updated)        print("rows inserted on second upsert:", again.rows_inserted)if __name__ == "__main__":    try:        main()    except Exception as exc:  # the redacted error is what a reader sees        print(safe_error(exc))        raise SystemExit(1)
출력python redeliver-hour-upsert.py
rows 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

One upsert call is not one commit: this one wrote 3 snapshots to update 20 rows and insert 1. The snapshot list shows what each one recorded.

The first snapshot is an overwrite. It deletes 500 rows, the rows of the hour-02 file, and adds back 480 of them unchanged. The next two are appends. The second adds 20 changed rows, and the third adds 1 row, the late row. The labels come from snapshot_labels, so the numbers are the commit order.

In the pyiceberg 0.12.0 source, upsert calls overwrite only when some rows changed, and append for the new rows only when there are some. overwrite writes two snapshots, a delete and an append. The library records the first as overwrite, because it also writes rows back. So a batch with changed and new rows adds three snapshots, one with only changed rows adds two, and one with only new rows adds one. Count them in the snapshot list, not from the library's call.

Running the same upsert again changes nothing: it reports 0 updated rows and 0 inserted. The second run finds every key already at its corrected value, so a correction sent twice does not change the table twice, which is what makes a retry safe.

Working rule: Use upsert with join_cols set to the key, and read its counts from the result. Count the snapshots from the snapshot list, and do not assume one commit per call. Run the same batch again when you are unsure whether the first write landed, and check that the second run reports no updates.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

MERGE in DuckLake

마지막으로 변경된 판: 2026.11.10판

DuckLake takes the same correction as a MERGE statement in SQL. A MERGE statement names the target table, the source batch and the key in its ON clause, and each WHEN clause says what to do with a matched or an unmatched row. The statement below is the one the example after it runs.

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)

The WHEN NOT MATCHED branch also inserts response_bytes, which is 0 in every row of the cut, so the late row's value is 0 too.

The AND t.views <> s.views condition matters. Without it, the MERGE would update and count every matched row, so a rerun would count them all again. With it, a matched row whose counts already agree is left alone and not counted. No example runs the statement without the condition, so the claim about a rerun without it is a reading of the statement, not a measured count.

merge-correction-ducklake.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""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."""import pyarrow as pafrom lib.lakehouse import hour_corrections, load_three_formats, new_warehouse, read_cut_hour, safe_error# The WHEN MATCHED condition is what keeps a rerun from counting matched rows that already agree.MERGE = """MERGE INTO lake.wiki.pageviews_hourly AS tUSING batch AS sON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_titleWHEN MATCHED AND t.views <> s.views THEN UPDATE SET views = s.viewsWHEN 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)"""def main():    with new_warehouse() as wh:        _, _, lake = load_three_formats(wh, range(6))        corrected = hour_corrections(read_cut_hour(2))        # a copy of the hour's first row, with a page title the table never held        late = corrected.slice(0, 1).set_column(            corrected.schema.get_field_index("page_title"),            "page_title",            pa.array(["Late_arrival_example"], type=pa.string()),        )        lake.register("batch", pa.concat_tables([corrected, late]))        print("source rows:", lake.execute("SELECT count(*) FROM batch").fetchall()[0][0])        # the join counts source rows whose key the table already holds, which splits the changes into inserts and updates        matched = lake.execute(            "SELECT count(*) FROM lake.wiki.pageviews_hourly AS t JOIN batch AS s "            "ON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_title"        ).fetchall()[0][0]        print("source rows matched:", matched)        # DuckDB returns one count for a MERGE, with updates and inserts added together        print("rows changed by the merge:", lake.execute(MERGE).fetchall()[0][0])        print("rows changed by the same merge again:", lake.execute(MERGE).fetchall()[0][0])        print("rows in table:", lake.execute("SELECT count(*) FROM lake.wiki.pageviews_hourly").fetchall()[0][0])if __name__ == "__main__":    try:        main()    except Exception as exc:  # the redacted error is what a reader sees        print(safe_error(exc))        raise SystemExit(1)
출력python merge-correction-ducklake.py
source rows: 501
source rows matched: 500
rows changed by the merge: 21
rows changed by the same merge again: 0
rows in table: 3000

Like the upsert, the merge is safe to rerun: it changes 21 rows the first time and 0 the second, and the table ends with 3000 rows, the six hours and the late row.

The changed count adds the two kinds of change together, so the split needs the source size. Of the 501 rows in the batch, 500 match a key already in the table, so the only row without a match is the late row. The rows inserted are the source rows minus the matched rows, here 501 minus 500. The rows updated are the changed rows minus the rows inserted. A count of matched rows alone gives neither number.

DuckLake is attached with inlining off in these examples, as chapter 1 explains, so each load writes data files rather than rows in the catalog. The merge's counts are of rows.

Working rule: Write a MERGE with a WHEN MATCHED AND condition that compares the columns you update, so that a rerun changes nothing. Make sure the source holds each key once before you run it. DuckLake refuses a merge that matches one target row to two source rows, and the production section shows the error.

도메인 테이블에서 변경된 레이블 병합하기

마지막으로 변경된 판: 2026.11.7판

이 책의 두 번째 테이블인 wiki.domains는 각 도메인 코드를 언어에 대응시킨다. 차원 테이블은 횟수가 아니라 레이블을 담고 있으며, 병합은 한꺼번에 바뀌는 소수의 레이블에 적합하다. 요점은 같은 구문 형태를 차원 테이블에도 쓸 수 있고, 조건에 관한 규칙도 여기에 똑같이 적용된다는 것이다.

UPDATE는 레이블을 변경할 것이다. MERGE 형태에는 WHEN NOT MATCHED 절도 있다. 이 절은 테이블에 아직 없는 도메인 코드를 삽입하므로, 도메인을 추가하는 피드에도 같은 구문을 쓸 수 있다. 이 테이블은 DuckLake에만 있으므로 병합도 DuckLake에서 실행한다. 페이지뷰 테이블은 DuckLake의 MERGE에서 DuckLake로 병합한다. 파이프라인에서는 여기서 병합한 레이블이 8장의 조인이 반환하는 레이블이 된다.

merge-domains-label.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""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."""import pyarrow as pafrom lib.lakehouse import attach_ducklake, connect_ducklake, print_rows, read_domains, new_warehouse, safe_errorMERGE = """MERGE INTO lake.wiki.domains AS tUSING labels AS sON t.domain_code = s.domain_codeWHEN MATCHED AND t.language <> s.language THEN UPDATE SET language = s.languageWHEN NOT MATCHED THEN INSERT (domain_code, language) VALUES (s.domain_code, s.language)"""def main():    with new_warehouse() as wh:        lake = connect_ducklake(wh.con)        attach_ducklake(lake, "lake", wh.root, inlining_row_limit=0)  # inlining off, so the rows land in data files        lake.execute("CREATE SCHEMA lake.wiki")        lake.execute("CREATE TABLE lake.wiki.domains (domain_code VARCHAR, language VARCHAR)")        lake.register("dims", read_domains())        lake.execute("INSERT INTO lake.wiki.domains SELECT * FROM dims")        # 'fr' is already in the table, so this label is an update and not an insert        lake.register("labels", pa.table({"domain_code": ["fr"], "language": ["French (France)"]}))        print("rows changed by the merge:", lake.execute(MERGE).fetchall()[0][0])        print("rows changed by the same merge again:", lake.execute(MERGE).fetchall()[0][0])        print_rows(lake.execute("SELECT domain_code, language FROM lake.wiki.domains").fetchall())  # sorted, so the order DuckLake returns rows in does not matterif __name__ == "__main__":    try:        main()    except Exception as exc:  # the redacted error is what a reader sees        print(safe_error(exc))        raise SystemExit(1)
출력python merge-domains-label.py
rows 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개의 행이 바뀌고, 같은 병합을 다시 실행하면 0개의 행이 바뀐다. 테이블은 이 책의 자체 데이터에 있는 네 개의 행으로 시작하며, 출력 끝의 정렬된 테이블은 각 도메인을 레이블과 함께 보여 준다.

작업 규칙: 차원 테이블도 팩트 테이블과 같은 WHEN MATCHED AND 조건으로 병합하고, 병합을 한 번 더 실행하여 아무것도 바뀌지 않는지 확인한다. 레이블 변경은 그 차원 테이블에 조인하는 모든 쿼리에 영향을 주므로, 병합하려는 레이블을 검토한다.

운영 환경에서 잘못되는 것

마지막으로 변경된 판: 2026.11.7판

정정 작업은 실제로 중복된 키, 단일 행 삭제 반복문, 이력을 읽는 사람이 놀라게 되는 스냅숏 수 때문에 잘못된다. 이 문제들은 쓰기 전에 확인하면 비용이 적게 들지만 나중에 찾아내면 비용이 크므로, 이 검사는 배치를 쓰는 작업 안에 두어야 한다.

배치 안의 중복된 키. 정정 행을 두 번 보내거나 잘못된 조인으로 같은 키를 가진 행이 둘 생기면 배치가 유효하지 않게 된다. 이 예제는 정정된 행 하나를 두 번 보내며, pyiceberg는 아무것도 쓰기 전에 업서트를 거부한다.

duplicate-source-keys.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""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."""import pyarrow as pafrom lib.lakehouse import KEY, hour_corrections, load_three_formats, new_warehouse, read_cut_hour, safe_error, scan_arrowMERGE = """MERGE INTO lake.wiki.pageviews_hourly AS tUSING batch AS sON t.hour_utc = s.hour_utc AND t.domain_code = s.domain_code AND t.page_title = s.page_titleWHEN MATCHED AND t.views <> s.views THEN UPDATE SET views = s.viewsWHEN 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)"""def main():    with new_warehouse() as wh:        iceberg, _, lake = load_three_formats(wh, range(6))        corrected = hour_corrections(read_cut_hour(2))        # A corrected row, sent twice: the batch holds two rows with one key.        before = read_cut_hour(2)["views"].to_pylist()  # the cut's views, to find the rows the correction changed        changed = [i for i, after in enumerate(corrected["views"].to_pylist()) if after != before[i]]        doubled = pa.concat_tables([corrected, corrected.slice(changed[0], 1)])        try:            iceberg.upsert(doubled, join_cols=list(KEY))            print("Iceberg upsert: no error")        except Exception as exc:            print("Iceberg upsert:", safe_error(exc, wh))  # safe_error replaces the warehouse path, so no local path is printed        print("Iceberg rows after the failed upsert:", scan_arrow(iceberg).num_rows)        lake.register("batch", doubled)        try:            lake.execute(MERGE)            print("DuckLake merge: no error")        except Exception as exc:            print("DuckLake merge:", safe_error(exc, wh))        print("DuckLake rows after the failed merge:", lake.execute("SELECT count(*) FROM lake.wiki.pageviews_hourly").fetchall()[0][0])if __name__ == "__main__":    try:        main()    except Exception as exc:  # the redacted error is what a reader sees        print(safe_error(exc))        raise SystemExit(1)
출력python duplicate-source-keys.py
Iceberg 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 업서트는 ValueError를 발생시키며, 테이블에는 여전히 2999개의 행이 있다. DuckLake 병합은 원인을 알려 주는 InvalidInputException를 발생시키는데, 그 원인은 대상 행 하나가 둘 이상의 원본 행과 일치했다는 것이다. 이때 테이블에는 여전히 2999개의 행이 있다. 오류를 잡아 같은 배치를 다시 시도하는 파이프라인은 다시 실패한다. 문제가 배치 자체에 있기 때문이다. 쓰기 전에 원본을 키 기준으로 중복 제거해야 한다. 키가 중복된 경우 Delta Lake의 병합은 여기서 시험하지 않았다(첫 번째 절 참조).

단일 행 삭제 반복문. Copy-on-write에서는 삭제마다 일치한 행이 든 파일을 다시 쓰는 커밋이 하나씩 생긴다. 반복문에서 삭제를 열 번 수행하면 일치한 행이 든 파일을 열 번 다시 쓰고, 스냅숏이나 버전이 열 개 남는다. 이는 여기서 측정한 값이 아니라 비용 모델이 시사하는 바이다. 삭제할 행을 모은 다음, 그 행들을 모두 포함하는 조건식으로 삭제를 한 번만 쓴다.

읽는 사람이 놀라게 되는 스냅숏 수. 변경된 행과 새 행이 함께 있는 업서트 한 번은 위의 실행에서 스냅숏을 3개 추가한다. 변경마다 커밋이 하나씩 있으리라 예상하는 독자는 이력이 변경 로그보다 길다는 것을 알게 된다. 스냅숏은 만료되기 전까지 테이블의 메타데이터에 남으며, 이는 7장에서 다룬다. 각 스냅숏은 자신이 참조하는 파일을 계속 유지한다.

알아차리는 방법. 이 문제들은 모두 이미 기록하고 있는 수치에 나타난다. pyiceberg 결과의 갱신된 행 수와 삽입된 행 수, 병합의 변경된 행 수는 보낸 배치와 일치해야 한다. 다시 실행했는데 변경이 보고된다면 배치가 생각한 내용과 다르다는 뜻이다. 스냅숏 수가 적재당 예상하는 스냅숏 수(업서트의 경우 최대 세 개)보다 빠르게 늘어난다면, append를 두 번 보내는 경우처럼 멱등하지 않은 재시도를 의심할 수 있다. 거부는 예외로 나타나므로, 예외를 잡고 계속 진행하는 작업은 정상으로 보이지만 테이블은 뒤처진 채로 남는다.

작업 규칙: 어떤 쓰기든 하기 전에 배치에 중복된 키가 있는지 확인하고, 거부를 일시적 오류가 아니라 배치의 버그로 취급한다. 삭제는 모아서 한 번에 쓴다. 정정을 감사할 때는 스냅숏 목록에서 스냅숏 수를 센다.

이 장에서 내린 결정

마지막으로 변경된 판: 2026.11.7판
  • 정정 데이터는 hour_utc, domain_code, page_title 키로 대조하며, 배치는 기록하기 전에 각 키를 한 번씩만 담고 있어야 한다.
  • 삭제 예제는 기준값으로 조회수 180을 사용한다. 이 절단은 각 시간대에서 조회수가 가장 높은 행만 남기므로, 기준값을 2로 두면 일치하는 행이 없기 때문이다.
  • Iceberg와 Delta Lake의 삭제는 쓰기 시 복사(copy-on-write) 방식이며, 이 예제들은 두 형식이 다시 쓰는 파일을 보여 준다. DuckLake의 DELETE는 삭제 파일을 기록하고 데이터 파일은 그대로 두며, 같은 예제가 이를 보여 준다.
  • 삭제 벡터는 사용하지 않는다. 고정한 버전에서 deltalake 1.6.6는 삭제 벡터를 기록하지 않으며, 이 기능을 활성화하면 to_pyarrow_table와 to_pyarrow_dataset가 해당 테이블을 거부한다.
  • 업서트와 병합은 두 번 실행하여 확인한다. 두 번째 실행에서는 바뀌는 행이 없다.
  • 스냅숏 수는 스냅숏 목록에서 읽는다. 이 장은 호출 한 번을 커밋 한 번으로 취급하지 않는다.
  • DuckLake 예제는 1장에서 설명한 대로 인라이닝을 끄므로, 집계된 수는 데이터 파일을 기준으로 한다.
  • 정정 데이터는 코드로 만들고 늦게 도착한 행은 생성한 것이므로, 이 예제들이 보여 주는 것은 쓰기 경로이지 실제 정정의 이력이 아니다.
  • 중복 키 예제는 거부 동작을 설명하지 않고 그 자체를 보여 주므로, 실패가 독자가 보는 출력에 나타난다.
  • 이 장에는 Delta Lake 업서트나 병합 예제가 없으므로, 삭제 외에 deltalake의 병합에 대해서는 어떤 주장도 하지 않는다.
  • 늦게 도착한 행과 정정 데이터는 한 배치에 함께 담기므로, 한 번의 호출로 갱신과 삽입을 모두 보여 준다.

이 판의 이 장

2026.11.10판예제 통과 2026년 11월 20이 장에서 5개 예제개 중 5개가 통과한다

영어판 2026.11.10판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

10장 중 5장: 삭제, 갱신, 병합으로 행 바로잡기

  1. 늦게 도착한 데이터는 정정으로 들어온다
  2. Delete rows, and what each format writes
  3. 카피 온 라이트와 머지 온 리드
  4. 수정된 시간대 upsert
  5. Upserts in pyiceberg
  6. MERGE in DuckLake
  7. 도메인 테이블에서 변경된 레이블 병합하기
  8. 운영 환경에서 잘못되는 것
  9. 이 장에서 내린 결정

맨 위로 돌아가기전체 장