-1

Using MERGE INTO, but getting rid of all duplicate rows whereas my expectation was it should behave like df.dropDuplicates()

Using Below MERGE INTO it's deleting all rows of duplicate which is leading to data loss for my use case.

DarkBee
14.4k9 gold badges86 silver badges135 bronze badges
asked Mar 27, 2025 at 7:05
1
  • Please provide enough code so others can better understand or reproduce the problem. Commented Mar 27, 2025 at 9:50

1 Answer 1

0

As a solution I am currently achieving it in below fashion

  1. create branch on iceberg table

  2. create data frame just selecting data from branch and apply window function Row_NUMBER() and select only records where rowNo is 2

  3. Execute MERGE INTO to delete the records from main table using data frame -- Upon it's completion execute step 4

  4. Execute MERGE INTO to insert distinct records from branch -- Upon it's completion execute step 5

  5. Drop the branch

spark.sql(
 """CREATE TABLE IF NOT EXISTS db.dedup_demo_part_drop
 (id BIGINT, name STRING, role STRING, salary double,joining_date STRING) USING iceberg PARTITIONED BY (joining_date)"""
 )
 
 
spark.sql(""" INSERT INTO db.dedup_demo values (1, 'Harry', 'Software Engineer', 25000,"2025年03月01日"), (2, 'John', 'Marketing Ops', 17000,"2025年03月01日")""") 
spark.sql("ALTER TABLE db.dedup_demo CREATE BRANCH duplicationTest")
spark.sql(""" describe db.dedup_demo """).show(false)
val df1 = spark.sql(""" select * from (SELECT id, name, role, salary,
 ROW_NUMBER() OVER (PARTITION BY id, name, role, salary ORDER BY id, name, role, salary DESC) AS rowNo
 FROM db.dedup_demo VERSION AS OF 'duplicationTest') where rowNo = 2 """)
 
df1.createOrReplaceTempView("source_deduplicate") 
spark.sql(""" MERGE INTO db.dedup_demo AS target
 USING source_deduplicate AS source
 ON target.id = source.id
 AND target.name = source.name
 AND target.role = source.role
 AND target.salary = source.salary
 WHEN MATCHED THEN
 DELETE
 """)
 
 
spark.sql("SELECT * FROM db.dedup_demo VERSION AS OF 'duplicationTest'").show(false) 
spark.sql(""" MERGE INTO db.dedup_demo AS target
 USING (select distinct * from db.dedup_demo VERSION AS OF 'duplicationTest') AS source
 ON target.id = source.id
 AND target.name = source.name
 AND target.role = source.role
 AND target.salary = source.salary
 WHEN NOT MATCHED THEN
 INSERT *
 """)
spark.sql(s"""ALTER TABLE ${tblName} DROP BRANCH ${branchName}""")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.