๐Ÿ“Š Data Engineering

Hudi

Apache Hudi

A data lake table format. Supports incremental processing and upserts.

Detailed Explanation

Apache Hudi (Hadoop Upserts Deletes and Incrementals) is an open-source table format that supports record-level updates, deletes, and incremental processing in data lakes. It was developed at Uber and is used in large-scale analytics workloads.

Key Features of Hudi

  • Upsert support: Record-level update and insert processing
  • Incremental queries: Efficiently query only changed data
  • ACID transactions: Guarantees data consistency
  • Time travel: Query data as of a past point in time
  • Automatic compaction: Automates file optimization

Hudi Table Types

TypeFeaturesUse case
Copy on Write (CoW)Rewrites entire files on writeRead-oriented, batch processing
Merge on Read (MoR)Writes to delta logs, merges on readWrite-oriented, real-time processing

Hudi vs Delta Lake vs Iceberg

FeatureHudiDelta LakeIceberg
Upsert performanceExcellent (indexing)GoodGood
Incremental queriesNative supportRequires CDFLimited
StreamingSpark/FlinkSpark-centricFlink excels
IndexingVarious indexesLimitedLimited

Code Example

Processing Hudi Upserts with PySpark

# PySpark๋กœ Hudi ํ…Œ์ด๋ธ” Upsert
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, lit, current_timestamp

# Spark ์„ธ์…˜ ์ƒ์„ฑ (Hudi ํŒจํ‚ค์ง€ ํฌํ•จ)
spark = SparkSession.builder \
    .appName("HudiUpsertExample") \
    .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") \
    .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.hudi.catalog.HoodieCatalog") \
    .config("spark.sql.extensions", "org.apache.spark.sql.hudi.HoodieSparkSessionExtension") \
    .getOrCreate()

# Hudi ํ…Œ์ด๋ธ” ์„ค์ •
hudi_options = {
    'hoodie.table.name': 'user_events',
    'hoodie.datasource.write.recordkey.field': 'event_id',
    'hoodie.datasource.write.partitionpath.field': 'event_date',
    'hoodie.datasource.write.precombine.field': 'updated_at',
    'hoodie.datasource.write.operation': 'upsert',
    'hoodie.datasource.write.table.type': 'COPY_ON_WRITE',
    'hoodie.upsert.shuffle.parallelism': 100,
    'hoodie.insert.shuffle.parallelism': 100,
    # ์ธ๋ฑ์‹ฑ ์„ค์ • (Upsert ์„ฑ๋Šฅ ํ–ฅ์ƒ)
    'hoodie.index.type': 'BLOOM',
    'hoodie.bloom.index.filter.dynamic.max.entries': 100000
}

# ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ์‚ฝ์ž…
initial_data = [
    ('evt_001', 'user_1', 'click', '2024-01-15', '2024-01-15 10:00:00'),
    ('evt_002', 'user_2', 'purchase', '2024-01-15', '2024-01-15 11:00:00'),
    ('evt_003', 'user_1', 'view', '2024-01-15', '2024-01-15 12:00:00')
]

df_initial = spark.createDataFrame(
    initial_data,
    ['event_id', 'user_id', 'event_type', 'event_date', 'updated_at']
)

# Hudi ํ…Œ์ด๋ธ”์— ์“ฐ๊ธฐ
df_initial.write \
    .format('hudi') \
    .options(**hudi_options) \
    .mode('overwrite') \
    .save('/data/hudi/user_events')

print("์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ ์‚ฝ์ž… ์™„๋ฃŒ")

# Upsert ๋ฐ์ดํ„ฐ (๊ธฐ์กด ๋ ˆ์ฝ”๋“œ ์—…๋ฐ์ดํŠธ + ์‹ ๊ทœ ์‚ฝ์ž…)
upsert_data = [
    # ๊ธฐ์กด ๋ ˆ์ฝ”๋“œ ์—…๋ฐ์ดํŠธ (event_type ๋ณ€๊ฒฝ)
    ('evt_001', 'user_1', 'purchase', '2024-01-15', '2024-01-15 14:00:00'),
    # ์‹ ๊ทœ ๋ ˆ์ฝ”๋“œ ์‚ฝ์ž…
    ('evt_004', 'user_3', 'signup', '2024-01-15', '2024-01-15 15:00:00'),
    ('evt_005', 'user_2', 'view', '2024-01-15', '2024-01-15 16:00:00')
]

df_upsert = spark.createDataFrame(
    upsert_data,
    ['event_id', 'user_id', 'event_type', 'event_date', 'updated_at']
)

# Upsert ์‹คํ–‰
df_upsert.write \
    .format('hudi') \
    .options(**hudi_options) \
    .mode('append') \
    .save('/data/hudi/user_events')

print("Upsert ์™„๋ฃŒ")

# ๊ฒฐ๊ณผ ํ™•์ธ
df_result = spark.read.format('hudi').load('/data/hudi/user_events')
df_result.show()

Incremental Query

# Hudi ์ฆ๋ถ„ ์ฟผ๋ฆฌ - ๋ณ€๊ฒฝ๋œ ๋ฐ์ดํ„ฐ๋งŒ ์กฐํšŒ
from datetime import datetime, timedelta

# ์ตœ๊ทผ ์ปค๋ฐ‹ ํƒ€์ž„์Šคํƒฌํ”„ ์กฐํšŒ
commits_df = spark.read \
    .format('hudi') \
    .load('/data/hudi/user_events') \
    .select('_hoodie_commit_time') \
    .distinct() \
    .orderBy('_hoodie_commit_time')

commits_df.show()

# ํŠน์ • ์‹œ์  ์ดํ›„ ๋ณ€๊ฒฝ ๋ฐ์ดํ„ฐ ์กฐํšŒ (์ฆ๋ถ„ ์ฟผ๋ฆฌ)
begin_time = '20240115100000'  # yyyyMMddHHmmss ํ˜•์‹

incremental_df = spark.read \
    .format('hudi') \
    .option('hoodie.datasource.query.type', 'incremental') \
    .option('hoodie.datasource.read.begin.instanttime', begin_time) \
    .load('/data/hudi/user_events')

print(f"{begin_time} ์ดํ›„ ๋ณ€๊ฒฝ๋œ ๋ ˆ์ฝ”๋“œ:")
incremental_df.show()

# ์‹ค์‹œ๊ฐ„ ํŒŒ์ดํ”„๋ผ์ธ์—์„œ ์ฆ๋ถ„ ์ฒ˜๋ฆฌ
def process_incremental_batch(last_commit_time):
    """๋งˆ์ง€๋ง‰ ์ฒ˜๋ฆฌ ์‹œ์  ์ดํ›„ ๋ฐ์ดํ„ฐ๋งŒ ์ฒ˜๋ฆฌ"""
    incremental_df = spark.read \
        .format('hudi') \
        .option('hoodie.datasource.query.type', 'incremental') \
        .option('hoodie.datasource.read.begin.instanttime', last_commit_time) \
        .load('/data/hudi/user_events')

    if incremental_df.count() > 0:
        # ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ์ฒ˜๋ฆฌ
        processed_df = incremental_df.groupBy('user_id') \
            .count() \
            .withColumnRenamed('count', 'event_count')

        # ๊ฒฐ๊ณผ ์ €์žฅ ๋˜๋Š” ์ „์†ก
        processed_df.write.mode('append').parquet('/data/processed/events')

        # ์ƒˆ๋กœ์šด ์ปค๋ฐ‹ ํƒ€์ž„์Šคํƒฌํ”„ ๋ฐ˜ํ™˜
        new_commit_time = incremental_df.select(
            max('_hoodie_commit_time')
        ).collect()[0][0]
        return new_commit_time

    return last_commit_time

Merge on Read (MoR) Tables and Compaction

# Merge on Read ํ…Œ์ด๋ธ” ์„ค์ •
mor_options = {
    'hoodie.table.name': 'realtime_events',
    'hoodie.datasource.write.recordkey.field': 'event_id',
    'hoodie.datasource.write.partitionpath.field': 'event_date',
    'hoodie.datasource.write.precombine.field': 'event_timestamp',
    'hoodie.datasource.write.operation': 'upsert',
    'hoodie.datasource.write.table.type': 'MERGE_ON_READ',
    # ๋น„๋™๊ธฐ ์ปดํŒฉ์…˜ ์„ค์ •
    'hoodie.compact.inline': 'false',
    'hoodie.compact.inline.max.delta.commits': 5,
    # ํด๋ฆฌ๋‹ ์„ค์ •
    'hoodie.cleaner.policy': 'KEEP_LATEST_COMMITS',
    'hoodie.cleaner.commits.retained': 10
}

# MoR ํ…Œ์ด๋ธ”์— ์ŠคํŠธ๋ฆฌ๋ฐ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ
streaming_df.writeStream \
    .format('hudi') \
    .options(**mor_options) \
    .option('checkpointLocation', '/checkpoints/realtime_events') \
    .outputMode('append') \
    .start('/data/hudi/realtime_events')

# MoR ํ…Œ์ด๋ธ” ์ฝ๊ธฐ - Snapshot Query (๋ณ‘ํ•ฉ๋œ ์ตœ์‹  ๋ฐ์ดํ„ฐ)
snapshot_df = spark.read \
    .format('hudi') \
    .option('hoodie.datasource.query.type', 'snapshot') \
    .load('/data/hudi/realtime_events')

# MoR ํ…Œ์ด๋ธ” ์ฝ๊ธฐ - Read Optimized Query (์ปดํŒฉ์…˜๋œ ๋ฐ์ดํ„ฐ๋งŒ)
read_optimized_df = spark.read \
    .format('hudi') \
    .option('hoodie.datasource.query.type', 'read_optimized') \
    .load('/data/hudi/realtime_events')

# ์ˆ˜๋™ ์ปดํŒฉ์…˜ ์‹คํ–‰
from hudi.spark import HoodieSparkClient

hudi_client = HoodieSparkClient(spark, '/data/hudi/realtime_events')
hudi_client.schedule_compaction()
hudi_client.run_compaction()

Hudi SQL (Spark SQL)

-- Hudi ํ…Œ์ด๋ธ” ์ƒ์„ฑ (Spark SQL)
CREATE TABLE user_profiles (
    user_id STRING,
    name STRING,
    email STRING,
    status STRING,
    updated_at TIMESTAMP
) USING hudi
TBLPROPERTIES (
    'hoodie.table.name' = 'user_profiles',
    'hoodie.datasource.write.recordkey.field' = 'user_id',
    'hoodie.datasource.write.precombine.field' = 'updated_at',
    'hoodie.datasource.write.operation' = 'upsert',
    'type' = 'cow'
)
PARTITIONED BY (status)
LOCATION '/data/hudi/user_profiles';

-- Upsert (MERGE INTO)
MERGE INTO user_profiles AS target
USING source_updates AS source
ON target.user_id = source.user_id
WHEN MATCHED THEN
    UPDATE SET
        name = source.name,
        email = source.email,
        status = source.status,
        updated_at = source.updated_at
WHEN NOT MATCHED THEN
    INSERT (user_id, name, email, status, updated_at)
    VALUES (source.user_id, source.name, source.email, source.status, source.updated_at);

-- ์‚ญ์ œ
DELETE FROM user_profiles WHERE status = 'deleted';

-- Time Travel ์ฟผ๋ฆฌ
SELECT * FROM user_profiles TIMESTAMP AS OF '2024-01-15 10:00:00';

-- ์ปค๋ฐ‹ ์ด๋ ฅ ์กฐํšŒ
CALL show_commits('user_profiles', 10);

Practical Conversation Example

Data Engineer: "We need to load CDC data into the data lake, but rewriting all the data every time is inefficient."
Senior Engineer: "Just use Hudi. With the Upsert operation, only the changed records are updated, and indexing finds the target records quickly."
Data Engineer: "Which is better, CoW or MoR?"
Senior Engineer: "If read performance matters, CoW is better; if writes are frequent, MoR is better. MoR writes quickly to delta logs and compacts later. But MoR has merge overhead when reading."
Data Engineer: "We have millions of updates a day, so I'm worried about performance."
Senior Engineer: "Hudi's BLOOM index should help. It quickly finds which file a record is in based on the record key. And if you design partitioning well, you can reduce the update scope."

Cautions

Choosing a Table Type

  • CoW rewrites entire files on write - slow on large partitions
  • MoR has degraded read performance when compaction is delayed
  • Choosing a type that fits the workload characteristics is essential

Indexing and Performance

  • BLOOM index can produce false positives - parameter tuning required
  • Efficient only when the record key distribution is uniform
  • Partitioning strategy has a major impact on Upsert performance

Operational Considerations

  • Configure compaction and cleaning scheduling appropriately
  • Monitoring is needed for the small files problem (Small Files)
  • Enabling the metadata table can improve performance

Related Terms

Learn More