Átomo
117Mg
Delta Lake · Spark

merge

Abrir na tabela

Definição

Upsert em tabela Delta: insere, atualiza e apaga numa única operação atómica.

whenNotMatchedBySource está disponível a partir do Delta 2.3.

Exemplos

1. Upsert
from delta.tables import DeltaTable

target = DeltaTable.forName(spark, "silver.customers")

(target.alias("d")
   .merge(stg.alias("s"), "d.customer_id = s.customer_id")
   .whenMatchedUpdateAll()
   .whenNotMatchedInsertAll()
   .execute())
2. Atualizar só o que mudou
(target.alias("d")
   .merge(stg.alias("s"), "d.customer_id = s.customer_id")
   .whenMatchedUpdateAll(condition="d.row_hash <> s.row_hash")
   .whenNotMatchedInsertAll()
   .execute())
3. Com exclusão (CDC)
(target.alias("d")
   .merge(cdc.alias("s"), "d.id = s.id")
   .whenMatchedDelete(condition="s.operation = 'D'")
   .whenMatchedUpdateAll()
   .whenNotMatchedInsertAll(condition="s.operation <> 'D'")
   .execute())

No mesmo grupo