Data Lakehouse
Data Lakehouse
An architecture that combines a data lake and a warehouse. A unified data platform supporting ACID transactions and schema management.
Data Lakehouse
An architecture that combines a data lake and a warehouse. A unified data platform supporting ACID transactions and schema management.
Data Lakehouse is a next-generation data architecture that combines the flexibility and scalability of a Data Lake with the data management capabilities and performance of a Data Warehouse. Traditionally, a two-tier architecture was common, in which raw data was stored in a Data Lake and data for analytics was separately ETLed into a Data Warehouse. A Lakehouse eliminates this redundant storage and complex data movement, and allows all data workloads to be handled on a single platform.
The core technologies of a Lakehouse are the open table formats Delta Lake, Apache Iceberg, and Apache Hudi. On top of object storage (S3, ADLS, GCS), they provide warehouse-level features such as ACID transactions, schema evolution, time travel, and concurrency control. This makes reliable data management possible while retaining the cost efficiency of file-based storage. In particular, a metadata layer makes it possible to manage Parquet files like tables.
A Lakehouse architecture can perform BI analytics, real-time streaming, and machine learning on a single copy of data, which ensures data consistency. In the past, data scientists worked with raw data in the Lake while analysts worked with refined data in the Warehouse, and this frequently caused the same metric to be calculated differently. A Lakehouse realizes a Single Source of Truth and thereby resolves this data silo problem.
Major Lakehouse platforms include Databricks (based on Delta Lake), Snowflake (with Iceberg support), AWS Lake Formation, and Google BigLake. They provide SQL query engines (Spark SQL, Trino, Presto), streaming processing (Structured Streaming), and ML workloads (MLflow, Feature Store) in an integrated manner. Recently, data governance and access control are also being strengthened through unified catalogs such as Unity Catalog and Nessie.
An example that uses ACID transactions, schema evolution, and time travel in a Delta Lake-based Data Lakehouse.
# Data Lakehouse ๊ตฌํ (Delta Lake ๊ธฐ๋ฐ)
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from delta import *
from delta.tables import DeltaTable
# Spark Session with Delta Lake
spark = SparkSession.builder \
.appName("DataLakehouse") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.config("spark.databricks.delta.retentionDurationCheck.enabled", "false") \
.getOrCreate()
LAKEHOUSE_PATH = "s3a://company-lakehouse"
# ============================================
# 1. Delta Table ์์ฑ (ACID ํธ๋์ญ์
์ง์)
# ============================================
def create_delta_table():
"""ํํฐ์
๊ณผ Z-Order ์ต์ ํ๊ฐ ์ ์ฉ๋ Delta ํ
์ด๋ธ ์์ฑ"""
# ์คํค๋ง ์ ์
schema = StructType([
StructField("order_id", StringType(), False),
StructField("customer_id", StringType(), False),
StructField("product_id", StringType(), False),
StructField("quantity", IntegerType(), True),
StructField("amount", DecimalType(10, 2), True),
StructField("order_date", DateType(), False),
StructField("status", StringType(), True),
StructField("region", StringType(), True)
])
# Delta ํ
์ด๋ธ ์์ฑ (SQL)
spark.sql(f"""
CREATE TABLE IF NOT EXISTS lakehouse.orders (
order_id STRING NOT NULL,
customer_id STRING NOT NULL,
product_id STRING NOT NULL,
quantity INT,
amount DECIMAL(10, 2),
order_date DATE NOT NULL,
status STRING,
region STRING
)
USING DELTA
PARTITIONED BY (order_date)
LOCATION '{LAKEHOUSE_PATH}/orders'
TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true',
'delta.dataSkippingNumIndexedCols' = '8'
)
""")
print("Delta table created with auto-optimization")
# ============================================
# 2. MERGE (Upsert) ์์
- CDC ์ฒ๋ฆฌ
# ============================================
def merge_cdc_data(cdc_df):
"""Change Data Capture๋ฅผ Delta ํ
์ด๋ธ์ ๋จธ์ง"""
delta_table = DeltaTable.forPath(spark, f"{LAKEHOUSE_PATH}/orders")
# MERGE INTO - Insert, Update, Delete ํ ๋ฒ์ ์ฒ๋ฆฌ
delta_table.alias("target").merge(
cdc_df.alias("source"),
"target.order_id = source.order_id"
).whenMatchedUpdate(
condition="source.operation = 'UPDATE'",
set={
"quantity": "source.quantity",
"amount": "source.amount",
"status": "source.status",
"region": "source.region"
}
).whenMatchedDelete(
condition="source.operation = 'DELETE'"
).whenNotMatchedInsert(
condition="source.operation = 'INSERT'",
values={
"order_id": "source.order_id",
"customer_id": "source.customer_id",
"product_id": "source.product_id",
"quantity": "source.quantity",
"amount": "source.amount",
"order_date": "source.order_date",
"status": "source.status",
"region": "source.region"
}
).execute()
print(f"Merged {cdc_df.count()} CDC records")
# ============================================
# 3. ์คํค๋ง ์งํ (Schema Evolution)
# ============================================
def evolve_schema():
"""๋ฌด์ค๋จ ์คํค๋ง ๋ณ๊ฒฝ"""
# ์ ์ปฌ๋ผ ์ถ๊ฐ (์๋ ์คํค๋ง ๋จธ์ง)
spark.sql(f"""
ALTER TABLE delta.`{LAKEHOUSE_PATH}/orders`
ADD COLUMNS (
discount_rate DECIMAL(5, 2) COMMENT 'ํ ์ธ์จ',
loyalty_points INT COMMENT '์ ๋ฆฝ ํฌ์ธํธ'
)
""")
# ์ปฌ๋ผ ํ์
๋ณ๊ฒฝ (์์ ํ ํ์ฅ๋ง ๊ฐ๋ฅ)
spark.sql(f"""
ALTER TABLE delta.`{LAKEHOUSE_PATH}/orders`
ALTER COLUMN amount TYPE DECIMAL(15, 2)
""")
# ์๋ ์คํค๋ง ๋จธ์ง๋ก ๋ฐ์ดํฐ ์ฐ๊ธฐ
new_data_with_extra_column = spark.createDataFrame([
("ORD-999", "CUST-1", "PROD-1", 2, 150.00, "2024-01-15", "completed", "์์ธ", 0.1, 150)
], ["order_id", "customer_id", "product_id", "quantity", "amount",
"order_date", "status", "region", "discount_rate", "loyalty_points"])
new_data_with_extra_column.write \
.format("delta") \
.mode("append") \
.option("mergeSchema", "true") \
.save(f"{LAKEHOUSE_PATH}/orders")
print("Schema evolved successfully")
# ============================================
# 4. Time Travel - ๊ณผ๊ฑฐ ๋ฐ์ดํฐ ์กฐํ
# ============================================
def time_travel_queries():
"""Delta Lake ํ์ ํธ๋๋ธ ๊ธฐ๋ฅ ํ์ฉ"""
# ํน์ ๋ฒ์ ์ ๋ฐ์ดํฐ ์กฐํ
df_version_5 = spark.read \
.format("delta") \
.option("versionAsOf", 5) \
.load(f"{LAKEHOUSE_PATH}/orders")
print(f"Version 5 record count: {df_version_5.count()}")
# ํน์ ์์ ์ ๋ฐ์ดํฐ ์กฐํ
df_yesterday = spark.read \
.format("delta") \
.option("timestampAsOf", "2024-01-14 00:00:00") \
.load(f"{LAKEHOUSE_PATH}/orders")
# ๋ฒ์ ๊ฐ ๋ณ๊ฒฝ ์ฌํญ ํ์ธ
changes = spark.sql(f"""
SELECT * FROM delta.`{LAKEHOUSE_PATH}/orders`
VERSION AS OF 10
EXCEPT
SELECT * FROM delta.`{LAKEHOUSE_PATH}/orders`
VERSION AS OF 9
""")
print(f"Changes between v9 and v10: {changes.count()} rows")
# ํ
์ด๋ธ ํ์คํ ๋ฆฌ ์กฐํ
history = spark.sql(f"DESCRIBE HISTORY delta.`{LAKEHOUSE_PATH}/orders`")
history.select("version", "timestamp", "operation", "operationMetrics").show(10)
# ์๋ชป๋ ๋ณ๊ฒฝ ๋กค๋ฐฑ
spark.sql(f"""
RESTORE TABLE delta.`{LAKEHOUSE_PATH}/orders`
TO VERSION AS OF 8
""")
print("Table restored to version 8")
# ============================================
# 5. ์ฑ๋ฅ ์ต์ ํ (Z-Order, OPTIMIZE)
# ============================================
def optimize_table():
"""์ฟผ๋ฆฌ ์ฑ๋ฅ ์ต์ ํ"""
# ํ์ผ ๋ณํฉ ๋ฐ ์ต์ ํ
spark.sql(f"""
OPTIMIZE delta.`{LAKEHOUSE_PATH}/orders`
WHERE order_date >= '2024-01-01'
""")
# Z-Order ํด๋ฌ์คํฐ๋ง (์์ฃผ ํํฐ๋ง๋๋ ์ปฌ๋ผ)
spark.sql(f"""
OPTIMIZE delta.`{LAKEHOUSE_PATH}/orders`
ZORDER BY (customer_id, product_id)
""")
# ๋ถํ์ํ ํ์ผ ์ ๋ฆฌ (Vacuum)
spark.sql(f"""
VACUUM delta.`{LAKEHOUSE_PATH}/orders`
RETAIN 168 HOURS -- 7์ผ ๋ณด์กด
""")
# ํ
์ด๋ธ ํต๊ณ ์์ง
spark.sql(f"ANALYZE TABLE delta.`{LAKEHOUSE_PATH}/orders` COMPUTE STATISTICS")
print("Table optimized with Z-Order clustering")
# ============================================
# 6. ์คํธ๋ฆฌ๋ฐ + ๋ฐฐ์น ํตํฉ (Unified Processing)
# ============================================
def unified_streaming_batch():
"""๋์ผ ํ
์ด๋ธ์์ ์คํธ๋ฆฌ๋ฐ๊ณผ ๋ฐฐ์น ๋์ ์ฒ๋ฆฌ"""
# ์คํธ๋ฆฌ๋ฐ ์ฐ๊ธฐ (Kafka -> Delta)
kafka_stream = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "kafka:9092") \
.option("subscribe", "orders") \
.load()
orders_stream = kafka_stream \
.select(from_json(col("value").cast("string"), order_schema).alias("data")) \
.select("data.*")
# Delta ํ
์ด๋ธ๋ก ์คํธ๋ฆฌ๋ฐ (ACID ๋ณด์ฅ)
query = orders_stream.writeStream \
.format("delta") \
.outputMode("append") \
.option("checkpointLocation", f"{LAKEHOUSE_PATH}/checkpoints/orders") \
.trigger(processingTime="1 minute") \
.start(f"{LAKEHOUSE_PATH}/orders")
# ๋์์ ๋ฐฐ์น ์ฝ๊ธฐ ๊ฐ๋ฅ (์คํธ๋ฆฌ๋ฐ๊ณผ ์ถฉ๋ ์์)
batch_df = spark.read.format("delta").load(f"{LAKEHOUSE_PATH}/orders")
daily_summary = batch_df \
.filter(col("order_date") == current_date()) \
.groupBy("region") \
.agg(
count("order_id").alias("orders"),
sum("amount").alias("revenue")
)
print("Streaming and batch processing running concurrently")
return query
# ============================================
# 7. Unity Catalog ํตํฉ (๊ฑฐ๋ฒ๋์ค)
# ============================================
def setup_governance():
"""Unity Catalog๋ก ๋ฐ์ดํฐ ๊ฑฐ๋ฒ๋์ค ์ค์ """
# ์นดํ๋ก๊ทธ ๋ฐ ์คํค๋ง ์์ฑ
spark.sql("CREATE CATALOG IF NOT EXISTS main")
spark.sql("CREATE SCHEMA IF NOT EXISTS main.sales")
# ๊ด๋ฆฌ ํ
์ด๋ธ ์์ฑ
spark.sql("""
CREATE TABLE IF NOT EXISTS main.sales.orders
USING DELTA
AS SELECT * FROM delta.`s3a://company-lakehouse/orders`
""")
# ์ด ์์ค ๋ณด์ (Column Masking)
spark.sql("""
ALTER TABLE main.sales.orders
ALTER COLUMN customer_id SET MASK mask_customer_id
""")
# ํ ์์ค ๋ณด์ (Row-Level Security)
spark.sql("""
ALTER TABLE main.sales.orders
SET ROW FILTER region_filter ON (region)
""")
# ์ ๊ทผ ๊ถํ ์ค์
spark.sql("GRANT SELECT ON TABLE main.sales.orders TO `analysts`")
spark.sql("GRANT ALL PRIVILEGES ON TABLE main.sales.orders TO `data_engineers`")
print("Governance policies applied via Unity Catalog")
# ============================================
# Lakehouse ํ์ดํ๋ผ์ธ ์คํ
# ============================================
if __name__ == "__main__":
create_delta_table()
evolve_schema()
optimize_table()
time_travel_queries()
setup_governance()
print("Data Lakehouse setup completed!")
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free