Sub topic 9
Upserting with foreachBatch and MERGE
This chapter assumes you can write a basic streaming query, know what a checkpoint is, and have used MERGE INTO on a Delta table. Streaming sinks usually append rows. A table of current customer records needs updates instead, and foreachBatch lets you run a MERGE for each micro-batch.
Why foreachBatch
The Delta streaming sink only appends. foreachBatch gives your function each micro-batch as a regular (non-streaming) DataFrame, plus a batch_id. Inside the function you can run any batch operation, including MERGE, writes to several tables, or calls to other systems.
A working upsert
The source table main.demo.customer_changes has the columns id, name and updated_at.
from pyspark.sql import Window, functions as F
def upsert(batch_df, batch_id):
latest = (
batch_df
.withColumn(
"rn",
F.row_number().over(
Window.partitionBy("id").orderBy(F.col("updated_at").desc())
),
)
.filter("rn = 1")
.drop("rn")
)
latest.createOrReplaceTempView("updates")
latest.sparkSession.sql("""
MERGE INTO main.demo.customers AS t
USING updates AS s
ON t.id = s.id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *
""")
(
spark.readStream.table("main.demo.customer_changes")
.writeStream
.foreachBatch(upsert)
.option("checkpointLocation", "/Volumes/main/demo/chk/customers_upsert")
.trigger(availableNow=True)
.start()
)The function does three things:
- It keeps only the newest row per
id. - It exposes that result as a temporary view.
- It merges the view into the target using SQL run on the batch's own session.
Common errors
- Multiple source rows match one target row.
MERGEfails when several rows in a batch share a key. Therow_numberstep prevents this. Without it, one busy key breaks the whole job. - Duplicates after a restart. Spark can replay the last batch if the query failed before recording it as committed. A
MERGEon a key is naturally idempotent, so replays give the same result. A plainINSERTorappendinsideforeachBatchwould write duplicates. - Wrong table in the view name. A temp view named
updatesis scoped to the batch session. Do not rely on it outside the function. - No output mode needed. Output modes apply to the built-in sinks.
foreachBatchreceives whatever rows the query produces for that batch.
Writing to more than one target
If the function writes to several tables, a failure partway through can leave some tables updated and others not. On replay, the whole function runs again. Make every write inside it idempotent. For writes that cannot be, use the Delta options txnAppId and txnVersion with batch_id so Delta skips a batch it has already written.
Exercise
A batch contains two rows with id 7, and the MERGE fails with an error about multiple matching source rows. How do you fix the function, and why is the fixed MERGE safe to replay after a restart?
Show answer
Deduplicate the batch to one row per key before the MERGE, for example with rownumber over a window partitioned by id and ordered by updatedat descending, keeping rn = 1. A replayed batch applies the same keyed updates and inserts, so the target ends in the same state.