오픈 테이블 포맷: Delta Lake와 Iceberg
공고 39건(42%)이 Databricks·Delta Lake·Iceberg를 언급합니다(대부분 우대사항). 둘 다 Parquet 파일 위에 "변경 기록(로그·메타데이터)"을 얹어 MERGE, 시간 여행, 스키마 변경을 가능하게 합니다. deltalake 1.6.6과 pyiceberg 0.12.0으로 같은 주문 데이터를 다뤘습니다.
Delta Lake
# L1. Delta Lake: 적재 → 추가 → MERGE(upsert) → 버전 기록 → 시간 여행 → 스키마 추가
import glob, duckdb, pyarrow as pa
from deltalake import DeltaTable, write_deltalake
def day(f): return duckdb.sql(f"SELECT *, ordered_at::DATE AS order_date FROM read_csv('{f}')").to_arrow_table()
files = sorted(glob.glob("../landing/orders/orders_2026-11-0[1-7].csv"))
path = "lake/orders_delta"
write_deltalake(path, pa.concat_tables([day(f) for f in files[:5]]), partition_by=["order_date"], mode="overwrite")
write_deltalake(path, pa.concat_tables([day(f) for f in files[5:]]), mode="append")
dt = DeltaTable(path)
upd = duckdb.sql("SELECT * EXCLUDE (ordered_at), ordered_at, ordered_at::DATE AS order_date FROM read_csv('../landing/orders/orders_2026-11-08_updates.csv')").to_arrow_table()
upd = upd.select(dt.to_pyarrow_table().schema.names)
res = (dt.merge(upd, predicate="t.order_id = s.order_id", source_alias="s", target_alias="t")
.when_matched_update_all().when_not_matched_insert_all().execute())
print("MERGE 결과:", {k: res[k] for k in ["num_target_rows_updated", "num_target_rows_inserted"]})
dt = DeltaTable(path)
for h in reversed(dt.history()):
print(f" 버전 {h['version']}: {h['operation']}")
for v in range(dt.version() + 1):
t = DeltaTable(path, version=v).to_pyarrow_table()
n_cancel = sum(1 for s in t.column("status").to_pylist() if s == "cancelled")
print(f" 버전 {v} 행 {t.num_rows:,} 취소 {n_cancel:,}")
# 스키마 추가: coupon 열이 생긴 새 데이터
new = duckdb.sql("SELECT 999001 AS order_id, 42 AS customer_id, 7 AS product_id, 1 AS qty, 'paid' AS status, TIMESTAMP '2026-11-09 10:00' AS updated_at, TIMESTAMP '2026-11-09 10:00' AS ordered_at, DATE '2026-11-09' AS order_date, 'WELCOME10' AS coupon").to_arrow_table()
try:
write_deltalake(path, new, mode="append")
except Exception as e:
print("스키마가 다르면 거부:", type(e).__name__, str(e).splitlines()[0][:120])
write_deltalake(path, new, mode="append", schema_mode="merge")
print("schema_mode='merge' 후 열:", DeltaTable(path).schema().to_arrow().names[-2:], "버전", DeltaTable(path).version())
print("DuckDB로 읽기:", duckdb.sql(f"SELECT count(*), count(coupon) FROM delta_scan('{path}')").fetchall())MERGE 결과: {'num_target_rows_updated': 3, 'num_target_rows_inserted': 0}
버전 0: WRITE
버전 1: WRITE
버전 2: MERGE
버전 0 행 22,250 취소 4,456
버전 1 행 32,200 취소 6,474
버전 2 행 32,200 취소 6,477
스키마가 다르면 거부: SchemaMismatchError Cannot cast schema, number of fields does not match: 9 vs 8
schema_mode='merge' 후 열: ['order_date', 'coupon'] 버전 3
DuckDB로 읽기: [(32201, 1)]
쓸 때마다 _delta_log/에 JSON 파일이 하나씩 쌓이고, 그 번호가 버전입니다. 취소 변경 3건은 MERGE로 덮어썼고(취소 6,474 → 6,477), 예전 버전을 그대로 다시 읽을 수 있습니다. 열이 하나 더 있는 데이터는 기본으로 거부되고, schema_mode="merge"를 줘야 받아들였습니다. 실수로 스키마가 바뀌는 것을 막는 기본값입니다.
Apache Iceberg
# L2. Apache Iceberg: 로컬 카탈로그(SQLite)로 테이블 만들기 → 추가 → upsert → 스냅샷 → 시간 여행 → 스키마 변경
import glob, os, duckdb, pyarrow as pa
from pyiceberg.catalog.sql import SqlCatalog
from pyiceberg.types import StringType
os.makedirs("lake/iceberg", exist_ok=True)
cat = SqlCatalog("local", uri="sqlite:///lake/iceberg/catalog.db", warehouse="file://" + os.path.abspath("lake/iceberg"))
cat.create_namespace_if_not_exists("shop")
if cat.table_exists("shop.orders"): cat.drop_table("shop.orders")
def load(pattern): return duckdb.sql(f"SELECT order_id::INT order_id, customer_id::INT customer_id, product_id::INT product_id, qty::INT qty, status, ordered_at, updated_at FROM read_csv('{pattern}')").to_arrow_table()
first = load("../landing/orders/orders_2026-11-0[1-5].csv")
tbl = cat.create_table("shop.orders", schema=first.schema)
tbl.append(first)
tbl.append(load("../landing/orders/orders_2026-11-0[6-7].csv"))
upd = load("../landing/orders/orders_2026-11-08_updates.csv").cast(tbl.schema().as_arrow())
r = tbl.upsert(upd, join_cols=["order_id"])
print("upsert 결과: 갱신", r.rows_updated, "추가", r.rows_inserted)
for s in tbl.snapshots():
t = tbl.scan(snapshot_id=s.snapshot_id).to_arrow()
print(f" 스냅샷 {s.snapshot_id} {s.summary.operation.value:9s} 행 {t.num_rows:,} 취소 {sum(1 for x in t.column('status').to_pylist() if x=='cancelled'):,}")
with tbl.update_schema() as u:
u.add_column("coupon", StringType())
print("스키마 변경 후 열:", [f.name for f in tbl.schema().fields][-2:])
print("메타데이터 파일:", os.path.relpath(tbl.metadata_location.replace("file://", "")))
print("DuckDB로 읽기:", duckdb.sql(f"SELECT count(*) FROM iceberg_scan('{tbl.metadata_location.replace('file://','')}')").fetchall())upsert 결과: 갱신 3 추가 0
스냅샷 4291413705246141088 append 행 22,250 취소 4,456
스냅샷 8897506796160344410 append 행 32,200 취소 6,474
스냅샷 8795439264868020725 overwrite 행 32,197 취소 6,474
스냅샷 4566599184717119577 append 행 32,200 취소 6,477
스키마 변경 후 열: ['updated_at', 'coupon']
DuckDB로 읽기: [(32200,)]
Iceberg는 카탈로그(여기서는 SQLite 파일)가 "지금 테이블의 메타데이터 파일이 어디인지"를 관리합니다. pyiceberg의 upsert는 바뀔 3행을 지우는 스냅샷(32,197행)과 새 값을 넣는 스냅샷 두 개를 남겼습니다. 한 트랜잭션으로 커밋되어 일반 조회는 최종 상태만 보지만, 시간 여행으로 중간 스냅샷을 열면 3행이 빠진 상태가 보입니다. 이력 테이블을 읽는 쪽에서 알아 둘 점입니다.
| Delta Lake | Apache Iceberg | |
|---|---|---|
| 변경 기록 | _delta_log/*.json | 메타데이터 JSON + 매니페스트, 카탈로그가 위치 관리 |
| 주로 쓰는 곳 | Databricks | Snowflake, AWS(Glue·Athena), Trino 등 여러 엔진 |
| 이 실습에서 | 버전 4개, MERGE, 스키마 병합 | 스냅샷 4개, upsert, 열 추가 |
직접 돌리지 않음: Databricks 작업 공간과 Unity Catalog는 계정이 없어 써 보지 않았습니다. 06장의 DuckLake와 함께, "Parquet + 변경 기록 + 카탈로그"라는 구조가 같다는 점을 기억하면 도구가 바뀌어도 따라갈 수 있습니다.
Delta와 Iceberg는 Parquet 위에 변경 기록을 얹어 MERGE·시간 여행·스키마 변경을 합니다. 스키마가 다르면 기본으로 거부되는지 먼저 확인합니다.