오래된 파일을 다시 쓰지 않고 파티셔닝 변경하기
읽는 데 약 25분분 걸린다, 7절에 4개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.10판을 번역한 것이다. 원문 읽기
이 장에서는 Iceberg, Delta Lake, DuckLake에서 테이블의 파티셔닝을 변경하고, 변경 전후에 쿼리가 계획하는 파일 수를 센다. 파티셔닝은 쿼리가 어떤 파일을 여는지 결정하므로, 파티셔닝을 바꾸면 모든 읽기 작업이 치르는 비용이 달라진다. 이미 기록된 파일에 변경이 어떤 영향을 미치는지는 포맷에 따라 다르다.
wiki.pageviews_hourly은 대시보드가 한 번에 한 시간씩 읽는 테이블이며 일 단위로 파티셔닝되어 있다. 문제는 이미 적재된 데이터를 다시 쓰지 않고 시간 단위로 다시 묶는 방법이다. 처음에 만든 시간별 적재 세 건은 이미 디스크에 있다. 그래서 팀은 02시 이후의 모든 적재에 시간 파티션을 적용하려 하며, 기존 적재 세 건을 복사하지 않고 변경이 이들에 어떤 영향을 주는지 알아야 한다.
변경에는 두 가지 비용이 든다. 첫째는 변경을 수행하는 작업량이며, 포맷이 기존 파일을 그대로 두는지에 달려 있다. 둘째는 이후의 모든 쿼리가 치르는 비용이다. 변경 시점에 걸치는 쿼리는 두 시기의 파일을 모두 계획하기 때문이다. 이 장에서는 각 라이브러리가 내놓는 수치로 두 비용을 모두 측정한다. 따라서 결정은 포맷에 대한 설명이 아니라 테이블이 실제로 하는 동작에 근거한다.
파티션 스펙도 버전으로 관리된다
파티션 스펙은 테이블이 행을 묶는 방식을 정한다. 예를 들어 hour_utc의 하루마다 한 그룹으로 묶을 수 있다. Iceberg에서 스펙은 테이블 메타데이터의 일부이고, 각 데이터 파일을 나열하는 매니페스트는 그 파일을 쓸 때 적용된 스펙을 기록한다. 스펙을 바꾸면 고유한 ID를 가진 두 번째 스펙이 만들어진다. 이후의 쓰기에는 두 번째 스펙이 쓰이며, 이미 디스크에 있는 파일은 쓰일 때의 스펙을 그대로 유지한다. Iceberg 명세에 따르면 변경된 스펙은 고유한 스펙 ID와 함께 테이블의 파티션 스펙 목록에 추가되고, 각 매니페스트는 자신을 쓸 때 사용한 스펙의 ID를 기록한다(partition_spec_id).
그 결과 테이블에는 두 개의 파티셔닝 시기가 나란히 존재한다. 쿼리는 열어 보는 파일마다 그 파일의 스펙을 읽으므로, 한 번의 스캔이 여러 스펙의 파일을 아우를 수 있다. 이 일은 플래너가 대신 처리한다. 따라서 변경의 비용은 쿼리가 반환하는 행이 아니라 실행 계획과 파일 수에 나타난다. hour_utc을 기준으로 작성한 쿼리는 스펙이 바뀌어도 텍스트가 그대로이며, 이것이 이 설계의 핵심이다. 달라지는 것은 플래너가 여는 파일의 집합이다. 이 장의 나머지 부분에서 두 가지를 모두 보인다.
스펙 변경은 메타데이터만 바꾼다. Iceberg는 자체 ID를 가진 스펙을 기록하고 데이터 파일은 그대로 둔다. 다음 절의 파일 수가 이를 보여 준다.
이전 스펙도 이력으로 남는다. 테이블은 지금까지 가졌던 모든 스펙의 기록을 보관하므로, 독자는 어떤 파일이 어떤 필드로 쓰였는지 언제든 알아낼 수 있다. 파티셔닝을 여러 번 바꾸는 팀에게 이 점은 중요하다. 각 파일이 자신의 스펙으로 "나는 어떻게 나뉘었는가?"라는 질문에 답하므로, 변경 순서를 누구도 기억할 필요가 없다. 기록은 메타데이터이므로 비용이 적게 들지만, 테이블의 스펙 목록은 변경할 때마다 길어진다.
나머지 두 포맷은 파티셔닝을 다르게 처리하며, 그 차이가 변경의 비용을 결정한다. Delta Lake는 파티션 컬럼을 이름으로 받으므로 쓰는 쪽이 이를 컬럼으로 만든다. DuckLake는 파티셔닝 키를 카탈로그에 보관한다. 각각은 다른 포맷을 다루는 절에서 다루며, 이 장의 나머지가 의존하는 Iceberg 단계 뒤에 온다.
작업 규칙: 독자의 필터가 바뀌고 현재 스펙이 그 필터에 비해 너무 많은 파일을 계획에 포함할 때 Iceberg 파티션 스펙을 변경한다. 현재 스펙이 그 필터에 대해 이미 적은 수의 파일만 계획한다면 그대로 둔다. 스펙을 변경할 때는 기존 파일을 그 자리에 둔다. 변경 사항은 날짜, 이전 필드와 대체 필드, 변경의 계기가 된 독자의 필터와 함께 테이블의 런북에 기록한다. 변경 전후의 계획 파일 수도 함께 보관하며, 이는 쿼리가 스캔하는 대상을 다루는 절에서 보인다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Move from daily to hourly partitions
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.
1"""Partition an Iceberg table by day, change its spec to hour, and load more hours under the new spec.23The two `data files` lines carry the point, one count for each spec.4"""56from collections import Counter78from pyiceberg.partitioning import PartitionField, PartitionSpec9from pyiceberg.transforms import DayTransform, HourTransform1011from lib.lakehouse import create_iceberg_table, new_warehouse, read_cut_hour, safe_error, scan_arrow121314def main():15 try:16 with new_warehouse() as wh:17 # source_id 1 is hour_utc, the table's first column: the day transform reads that column18 day_spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="ts_day"))19 table = create_iceberg_table(wh, partition_spec=day_spec)20 for hour in range(3): # hours 00 to 02, written under the day spec21 table.append(read_cut_hour(hour))2223 # hour_utc is the source of the hour field too, as it was of the day field24 with table.update_spec() as update:25 update.remove_field("ts_day")26 update.add_field("hour_utc", HourTransform(), "ts_hour")27 for hour in range(3, 6): # hours 03 to 05, written under the hour spec28 table.append(read_cut_hour(hour))2930 # the labels number the specs in the order they were made, so the output names no spec ID31 specs = sorted(table.specs())32 labels = {spec_id: f"spec {number}" for number, spec_id in enumerate(specs, start=1)}33 for spec_id in specs:34 for field in table.specs()[spec_id].fields:35 print(f"{labels[spec_id]} field {field.name}: transform {field.transform}")3637 # group the data files by the spec_id each one carries38 files = Counter(table.inspect.data_files().column("spec_id").to_pylist())39 for spec_id in specs:40 print(f"{labels[spec_id]} data files: {files[spec_id]}")41 print(f"rows in table: {scan_arrow(table).num_rows}")42 except Exception as exc:43 print(safe_error(exc))44 raise SystemExit(1)454647if __name__ == "__main__":48 main()
python day-then-hour-spec.pyspec 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.
각 스펙으로 기록된 파일
각 데이터 파일은 그 파일이 기록된 시점의 스펙에 속하므로, 스펙별로 파일 수를 세면 각 파일이 어느 시기의 것인지 알 수 있다. 데이터 파일 목록에는 각 파일의 스펙 ID가 들어 있으므로, 이 집계는 파일을 스펙별로 묶어 "spec 1"과 "spec 2"라는 레이블 아래에 스펙마다 하나씩 개수를 낼 수 있다. 레이블은 스펙이 만들어진 순서대로 번호를 매긴 것이므로, 출력에는 스펙 ID가 나타나지 않는다.
일 단위로 파티셔닝된 세 번의 로드는 스펙을 변경한 뒤에도 파일이 그대로 유지되었다. 출력에는 spec 1 아래에 3 데이터 파일이, spec 2 아래에 3 데이터 파일이 나타난다. 따라서 시 단위로 파티셔닝된 세 번의 로드가 각자의 파일을 기록했으며, 스펙 변경 자체는 아무것도 기록하지 않았다. 변경 후에 spec 1의 개수가 줄었다면 무언가가 그 파일들을 다시 썼다는 뜻이며, 이전 시기의 데이터를 신뢰하기 전에 그 원인을 찾아야 한다.
작업 규칙: 스펙을 변경한 뒤에는 항상 각 스펙 아래의 데이터 파일 수를 세고, 그 수를 수행한 로드와 비교한다. 다시 쓰기를 계획하지 않았는데 개수가 변했다면, 그 변경이 의도한 것보다 더 많은 일을 했다는 뜻이다. 다음 로드를 하기 전에 멈추고 확인한다.
쿼리가 스캔하는 대상 확인하기
파티션 스펙은 파일을 건너뛰기 위한 방법이다. 쿼리가 파일을 읽기 전에 플래너는 파일의 파티션 값과 컬럼 경계값을 살펴보고, 필터와 일치할 수 없는 파일을 제외한다. 쿼리의 비용은 플래너가 계획에 넣지 않은 파일이 얼마나 되느냐에 달려 있다. 따라서 변경을 검증하는 방법은 행을 비교하는 것이 아니라, 대표적인 필터가 변경 전후에 계획하는 파일 수를 세는 것이다. 스캔을 계획하면 행을 읽지 않고도 파일 목록이 반환되므로, 이 개수는 변경할 때마다 실행해도 될 만큼 비용이 적다.
가지치기(pruning)는 변경의 효과가 나타나는 지점이므로, 세 가지 스캔을 두 번 계획한다. 한 번은 일 단위 스펙에서(시간 단위 파티션으로 옮기기 참고), 다른 한 번은 시간 단위로 파티셔닝한 적재 세 번을 마친 뒤에 계획한다. 두 필터는 각각 한 시간을 요청한다. 하나는 변경 전에 적재된 01시이고, 다른 하나는 변경 후에 적재된 04시이다. 세 번째는 필터가 없는 전체 스캔이다.
1"""Count the files an Iceberg scan plans for one hour, for another hour and for the whole table, before and after a spec change.23The filtered counts are the lines to compare, one pair for each filter.4"""56from pyiceberg.partitioning import PartitionField, PartitionSpec7from pyiceberg.transforms import DayTransform, HourTransform89from lib.lakehouse import create_iceberg_table, hour_filter, new_warehouse, read_cut_hour, safe_error101112def plan_counts(table):13 """Return the files planned for hour 01, for hour 04 and for no filter, in that order."""14 # plan_files gives the planned files as a list; each printed count is that list's length15 one_hour = len(table.scan(row_filter=hour_filter(1)).plan_files())16 # hour 04 is loaded only after the change, so the filter can match only an hour-partitioned file17 hour_four = len(table.scan(row_filter=hour_filter(4)).plan_files())18 everything = len(table.scan().plan_files())19 return one_hour, hour_four, everything202122def main():23 try:24 with new_warehouse() as wh:25 day_spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=DayTransform(), name="ts_day"))26 table = create_iceberg_table(wh, partition_spec=day_spec)27 for hour in range(3): # hours 00 to 02, under the day spec28 table.append(read_cut_hour(hour))29 one_hour, hour_four, everything = plan_counts(table)30 print(f"before the change, one-hour filter plans: {one_hour}")31 print(f"before the change, hour 04 filter plans: {hour_four}")32 print(f"before the change, no filter plans: {everything}")3334 with table.update_spec() as update:35 update.remove_field("ts_day")36 update.add_field("hour_utc", HourTransform(), "ts_hour")37 for hour in range(3, 6): # hours 03 to 05, under the hour spec38 table.append(read_cut_hour(hour))39 one_hour, hour_four, everything = plan_counts(table)40 print(f"after the change, one-hour filter plans: {one_hour}")41 print(f"after the change, hour 04 filter plans: {hour_four}")42 print(f"after the change, no filter plans: {everything}")43 except Exception as exc:44 print(safe_error(exc))45 raise SystemExit(1)464748if __name__ == "__main__":49 main()
python plan-files-by-partition.pybefore the change, one-hour filter plans: 1
before the change, hour 04 filter plans: 0
before the change, no filter plans: 3
after the change, one-hour filter plans: 1
after the change, hour 04 filter plans: 1
after the change, no filter plans: 6
| 단계 | 한 시간 필터 | 04시 필터 | 필터 없음 |
|---|---|---|---|
| 변경 전, 일 단위 파티션 적재 세 번 | 1 | 0 | 3 |
| 변경 후, 시간 단위 파티션 적재 세 번 추가 | 1 | 1 | 6 |
각 필터는 해당 시간이 어느 시기에 적재되었든 그 시간의 파일에 도달한다. 한 시간 필터가 계획하는 파일은 변경 전 1개, 변경 후 1개이고, 04시 필터가 계획하는 파일은 변경 전 0개, 변경 후 1개이다. 01시는 변경 전에 적재되었으므로 두 계획에 모두 들어 있는 파일 하나는 그 시간의 일 단위 파티션 파일이다. 변경 전에는 세 파일이 하루를 공유하므로, 플래너는 hour_utc 경계값만으로 나머지 두 파일을 건너뛸 수 있다. 변경 후에는 시간 단위로 파티셔닝된 세 파일도 건너뛴다. 04시는 반대 방향으로 작동한다. 이 시간을 담고 있는 일 단위 파티션 파일은 없으므로, 일치하는 파일은 그 시간을 담은 시간 단위 파티션 파일뿐이다. 이 개수만으로는 플래너가 파티션 값으로 파일을 건너뛰었는지 컬럼 경계값으로 건너뛰었는지 알 수 없다. 개수가 보여 주는 것은 계획에 남은 파일뿐이다.
계획 개수는 바이트가 아니라 파일의 개수이다. 파일마다 크기가 다르므로 개수가 같은 두 계획이 읽는 데이터의 양은 다를 수 있다. 그래도 개수는 플래너가 판단하는 기준이므로 가장 먼저 확인할 값으로 적절하다. 개수가 일치하는데도 쿼리가 느리다면 파일 크기와 쿼리 자체를 살펴본다.
전체 스캔은 테이블이 쓴 모든 파일의 비용을 치른다. 전체 스캔의 계획은 3개에서 6개로 늘어나는데, 일 단위 파티션 파일에 시간 단위 파티션 파일이 더해진 결과이다. 이 증가는 기존 파일을 그대로 두는 데 드는 비용이며, 필터가 있는 스캔뿐 아니라 전체 스캔도 세어야 하는 이유이다.
작업 규칙: 파티션을 변경할 때마다 그 전후에 독자가 쓰는 필터와 전체 스캔을 계획하고, 그 개수를 런북 항목과 함께 보관한다. 파일 하나를 계획하던 필터가 여러 파일을 계획하기 시작했다면, 그 변경이 해당 필터의 가지치기를 망가뜨린 것이므로, 그 스펙으로 다음 적재를 하기 전에 스펙이나 필터를 바꿔야 한다.
다른 형식의 파티셔닝
나머지 두 형식에서는 같은 변경에 드는 비용이 다르지만, 세 형식 모두 다시 읽은 행은 같다. 달라지는 것은 파일과 계획이다. 아래 표는 세 형식을 요약한 것이다.
| 형식 | 변경 방법 | 이미 기록된 파일 | 변경 후 확인할 것 |
|---|---|---|---|
| Iceberg | update_spec() 블록 하나 |
유지되며, 이전 스펙 아래에 그대로 남는다 | 스펙별 파일 수, 계획 수 |
| Delta Lake | schema_mode="overwrite"를 사용한 전체 덮어쓰기 |
이후 버전에서 다시 기록되며, 이전 버전은 유지된다 | 행 수, 파일 수, 이전 버전의 파티션 열 |
| DuckLake | ALTER TABLE ... SET PARTITIONED BY |
유지되며, 설정은 이후의 적재에 적용된다 | 한 번 적재한 뒤의 파일 수, 파티션 키 |
Delta Lake는 일반 열로 파티셔닝하며, 파티션 옵션은 표현식이 아니라 열 이름을 받는다. Delta Lake 프로토콜은 partitionColumns를 데이터를 파티셔닝하는 열 이름들을 담은 배열로 정의한다. 생성 열(generated column)로 테이블 안에서 day이나 hour을 계산할 수 있지만, 그렇게 하면 테이블의 기록기(writer) 프로토콜 버전이 올라가므로, 이 책에서는 둘 다 기록기에서 계산한다. 도우미 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 플래그 대신 사용하는 것이다. 덮어쓰기는 테이블이 가진 모든 행을 교체하므로, 덮어쓰기를 시작하기 전에 행을 메모리로 읽어 둔다. 행을 다시 기록하는 것이 행을 보존하는 유일한 방법이다.
1"""Change a Delta Lake table's partition columns from day to hour, which rewrites the table.23Read the error line from the plain overwrite first, then the version and row lines after the rewrite.4"""56import pyarrow.compute as pc7from deltalake import DeltaTable, write_deltalake89from lib.lakehouse import delta_file_count, new_warehouse, read_cut_hour, read_delta, safe_error101112def with_partition_columns(rows):13 """Add the day and hour columns that Delta partitions by. Delta partitions only by plain columns."""14 rows = rows.append_column("day", pc.strftime(rows["hour_utc"], format="%Y-%m-%d"))15 # %H is the 24-hour clock, zero-padded, so hour 04 is the string "04"16 return rows.append_column("hour", pc.strftime(rows["hour_utc"], format="%H"))171819def main():20 try:21 with new_warehouse() as wh:22 path = f"{wh.root}/delta/pageviews_hourly"23 for hour in range(3):24 write_deltalake(path, with_partition_columns(read_cut_hour(hour)), partition_by=["day"], mode="append")25 table = DeltaTable(path)26 print(f"partition columns before: {table.metadata().partition_columns}")27 print(f"version before: {table.version()}")28 print(f"data files before: {delta_file_count(table)}")2930 # read first, so the rows are in memory before the overwrite below writes them back31 rows = read_delta(path)32 try:33 # no schema_mode here, so the library refuses the change and the error is printed34 write_deltalake(path, rows, partition_by=["hour"], mode="overwrite")35 except Exception as exc:36 print(f"change without schema mode: {safe_error(exc, wh)}")3738 # schema_mode is what lets the partition columns change in a full overwrite39 write_deltalake(path, rows, partition_by=["hour"], mode="overwrite", schema_mode="overwrite")40 table = DeltaTable(path)41 print(f"partition columns after: {table.metadata().partition_columns}")42 print(f"version after: {table.version()}")43 print(f"data files after: {delta_file_count(table)}")44 print(f"rows after: {read_delta(path).num_rows}")4546 # version 2 is the last version before the rewrite; Delta counts versions from 047 old = DeltaTable(path, version=2)48 print(f"partition columns in version 2: {old.metadata().partition_columns}")49 print(f"rows in version 2: {read_delta(path, version=2).num_rows}")50 except Exception as exc:51 print(safe_error(exc))52 raise SystemExit(1)535455if __name__ == "__main__":56 main()
python delta-partition-overwrite.pypartition 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의 변경은 메타데이터 편집이 아니라 테이블의 현재 파일을 다시 쓰는 작업이다. 여기의 테이블은 작다. 큰 테이블에서는 같은 다시 쓰기가 그 크기만큼의 비용을 치르므로, 읽기 허용 시간대(read window)를 둔 유지보수 작업으로 계획해야 한다. 쓰기 전에 모든 행을 메모리로 읽어 들이기도 하므로, 다시 쓰기에는 테이블 전체가 한꺼번에 들어갈 공간이 필요하다. 메모리에 담기지 않는 테이블이라면 새 위치로 복사하는 쪽이 더 안전하며, 그런 복사를 확인하는 방법은 9장에서 보인다.
DuckLake는 파티셔닝을 카탈로그의 테이블 설정으로 저장하며, 변경은 이후의 적재에만 적용된다. DuckLake 문서는 테이블의 파티셔닝 키가 변경 이후에 기록되는 데이터에만 영향을 준다고 설명한다. 테이블을 hour(hour_utc)로 파티셔닝하도록 설정하고 한 시간 분량을 더 적재하면, 그 적재 전후의 파일 수가 이 규칙이 작동하는 모습을 보여 준다. 도우미는 인라이닝을 끈 상태로 카탈로그를 연결하므로 적재마다 데이터 파일이 기록되고, 파일 수는 각 적재가 한 일을 보여 준다.
1"""Set a DuckLake table's partitioning to hour, then load one more hour and count the files before and after it.23The files-kept line is the one to check: it counts the earlier files still listed after the hour load.4"""56from lib.lakehouse import (DUCKLAKE_ALIAS, NAMESPACE, TABLE, connect_ducklake, create_ducklake_table, ducklake_file_count,7 ducklake_file_paths, new_warehouse, read_cut_hour, safe_error)8910def load(con, hour):11 con.register("batch", read_cut_hour(hour))12 con.execute(f"INSERT INTO {DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE} SELECT * FROM batch")13 con.unregister("batch")141516def main():17 try:18 with new_warehouse() as wh:19 con = connect_ducklake(wh.con)20 # the helper leaves inlining off by default, so every load below writes one data file21 create_ducklake_table(con, wh.root)22 for hour in range(3): # hours 00 to 02, before the change23 load(con, hour)24 print(f"data files before the change: {ducklake_file_count(con, DUCKLAKE_ALIAS, TABLE)}")25 before = ducklake_file_paths(con, DUCKLAKE_ALIAS, TABLE)2627 con.execute(f"ALTER TABLE {DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE} SET PARTITIONED BY (hour(hour_utc))")28 load(con, 3) # hour 03, the first load after the change29 print(f"data files after one load under hour: {ducklake_file_count(con, DUCKLAKE_ALIAS, TABLE)}")30 after = ducklake_file_paths(con, DUCKLAKE_ALIAS, TABLE)31 # the intersection is the earlier files still listed after the hour load32 print(f"files kept from before the change: {len(before & after)}")3334 # ordered by key index, so the keys print in a fixed order35 for key, transform in con.execute(36 "SELECT partition_key_index, transform FROM __ducklake_metadata_lake.ducklake_partition_column ORDER BY 1"37 ).fetchall():38 print(f"partition key {key}: transform {transform}")39 rows = con.execute(f"SELECT count(*) FROM {DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}").fetchall()40 print(f"rows in table: {rows[0][0]}") # count(*) returns one row with one value41 except Exception as exc:42 print(safe_error(exc))43 raise SystemExit(1)444546if __name__ == "__main__":47 main()
python ducklake-partition-alter.pydata 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개를 가졌으므로, 시간 적재는 파일 하나를 기록했다. 그 적재 뒤에 나열된 파일 중 3개는 이미 적재 전에도 나열되어 있었다. 앞선 세 번의 적재는 다시 쓰이지 않았으며, 이것이 문서의 규칙이 실제로 뜻하는 바다. 카탈로그에는 변환 hour을 가진 파티션 키 하나가 나열되고, 테이블은 1999개의 행을 가진다.
작업 규칙: Iceberg와 DuckLake에서 파티션 변경은 메타데이터의 변경이다. 이전 파일은 그대로 남고 이후의 적재는 변경이 설정한 파티셔닝을 사용하므로, 첫 적재 뒤에 파일 수를 확인한다. Delta Lake에서 파티션 변경은 테이블의 현재 파일을 다시 쓰는 전체 덮어쓰기이므로, 다시 쓰기로 계획하고 그 뒤에 행 수와 파일 수를 확인한다.
운영 환경에서 문제가 생기는 지점
파티션 변경은 변경 자체에서 실패하는 일이 드물다. 문제는 이후의 적재와 계획 단계에서 나타난다.
먼저 누락된 패키지가 있다. 시간 단위 파티션으로 옮기는 절에서 정한 버전 고정 아래에서 일 변환과 시간 변환에는 pyiceberg-core가 필요하며, 변환은 데이터를 쓸 때 이 패키지를 가져온다. pyiceberg만 설치한 환경에서는 테이블을 만들 수는 있지만, 시간 변환이 적용된 상태에서 처음 append를 하면 실패한다. 이 실패는 스펙을 바꿀 때가 아니라 처음 예약된 적재 때 드러난다. 그래서 버전 고정은 설치에 대한 누군가의 기억이 아니라 requirements 파일에 있어야 한다.
다음은 과도한 파티셔닝이다. 필터에 필요한 것보다 세밀한 파티션 단위를 쓰면 쿼리마다 열어야 할 파일이 늘어나고, 파일 하나가 담는 행은 줄어든다. 한 번에 수백 행씩 시간 단위로 적재하면 절대적인 크기로 볼 때 작은 파일이 생긴다. 이것은 측정값이 아니라 경험칙이며, 비용은 저장소와 엔진에 따라 달라진다. 쿼리가 스캔하는 대상에 관한 절의 계획 수는 각 스펙에서 쿼리가 파일을 몇 개 여는지 보여 준다. 적재할 때마다 전체 스캔 수가 계속 늘어나는데 파일당 행 수는 작게 유지된다면 이것이 징후이다. 해결책은 컴팩션이며 이는 6장에서 다룬다. 또는 이후의 적재에 더 굵은 단위를 쓰는 것이다.
세 번째는 카디널리티가 높은 키이다. page_title에 대한 아이덴티티 파티션은 제목마다 파티션을 하나씩 만들고, 각 적재는 그 안에 포함된 모든 제목에 대해 파일을 하나씩 쓴다. 여기서 쓰는 테이블은 행이 수천 개뿐이지만, 실제 페이지 테이블에는 제목이 이보다 훨씬 많고 파일 수는 시간이 아니라 제목 수를 따라 늘어난다. 필터가 사용하는 시간을 기준으로 파티션을 나누고, 제목은 쿼리가 필터링하는 일반 열로 남겨 둔다.
그다음은 결과만으로 변경을 판단하는 경우이다. 파티션을 바꾸기 전과 후의 행은 같으므로, 행을 비교하는 검사는 변경이 쓸모가 있었는지와 상관없이 통과한다. 이 장의 예제는 아무것도 유실되지 않았음을 확인하려는 목적으로만 행을 출력한다. 변경을 보여 주는 것은 개수이다.
마지막은 독자가 사용하는 테이블에 대해 실행하는 재작성이다. 이 장의 Delta 예제는 단독으로 실행되며, 쓰는 도중의 독자를 시험하지 않는다. 독자가 의존하는 테이블이라면 재작성을 사본에 쓰고, 사본의 개수와 행을 확인한 다음, 독자가 그 사본을 가리키게 하기를 권한다. 9장은 형식 사이에서 같은 검사를 사용한다. 이 권고는 판단에 따른 것이며, 이를 측정하는 예제는 없다.
작업 규칙: 파티션 단위는 데이터가 도착하는 빈도가 아니라, 독자가 사용하는 필터와 예상되는 파일 크기를 기준으로 선택한다. 독자가 사용하는 테이블에 파티션 변경을 실행하기 전에 사본에서 먼저 실행하고, 양쪽의 계획 수와 행 수를 비교한다.
이 장에서 내린 결정
- Iceberg 테이블은
hour_utc의 day 변환과 hour 변환으로 파티셔닝하고,pyiceberg-core를pyiceberg와 함께 고정한다. 이 변환은 시간 열을 파티션 원본으로 유지하므로, 시간에 대한 필터가 기록기가 사용한 것과 같은 필드를 읽는다. 시간으로 필터링하는 모든 테이블에 이 방식을 권장한다. - Delta Lake 테이블은
schema_mode="overwrite"를 사용한 전체 덮어쓰기로 변경하고, 파티션 열은 기록기가 계산한 일반 문자열 열인day와hour으로 기록한다. 이 라이브러리에서는 파티션을 바꾸려면 전체 덮어쓰기가 필요하므로 다시 쓰는 비용을 감수한다. - 파일 수와 계획은 각 라이브러리가 제공하는 자체 목록 기능으로 센다. Iceberg는
plan_files(), Delta Lake는file_uris(), DuckLake는ducklake_list_files를 사용한다. 파일 이름에는 실행할 때마다 달라지는 무작위 ID가 들어 있으므로, 어떤 예제도 파일 이름을 출력하지 않는다. - 파일 수를 세는 모든 예제에서는 1장에서 설명한 대로 DuckLake의 인라이닝을 끈다. 그러면 파일 수는 곧 데이터 파일의 수가 된다.
- hour 단위는 로드가 도착하는 빈도가 아니라, 한 번에 한 시간씩 읽는 대시보드의 필터를 기준으로 정한다.
- Delta의 실패를 먼저 보여 준 다음 해결책을 보여 준다. 이렇게 하면 스키마 설정을 요구하는 오류를 통해 그 설정을 설명할 수 있다.
- DuckLake의 파티션 키는 파일 이름이 아니라 카탈로그의 파티션 테이블에서 출력한다. 그러면 파일 이름이 바뀌어도 출력이 달라지지 않는다.
- 출력에는 필드 레이블과 스펙 레이블을 남기고, 스펙 ID, 스냅숏 ID, 파일 이름은 출력하지 않는다. 스냅숏 ID와 파일 이름은 실행할 때마다 다르며, 레이블을 보면 독자가 ID를 해독하지 않아도 스펙이 어느 시기에 속하는지 알 수 있다.
이 판의 이 장
2026.11.10판예제 통과 2026년 11월 20이 장에서 4개 예제개 중 4개가 통과한다
영어판 2026.11.10판을 번역한 것이다.