Skip to main content
PYSPARK โ€ข LESSON 187

Natural Key Deduplication with Window row_number()

How do we deduplicate duplicate orders by partitioning on order_id and keeping the latest updated_at record?

Productionโฑ 3 Minutesโญ 1380 XP
๐Ÿค” THE QUESTION

How do we deduplicate duplicate orders by partitioning on order_id and keeping the latest updated_at record?

๐Ÿ’ก WHAT IS IT?

Partitioning by natural business key, ordering by update timestamp descending, and filtering for row_number == 1.

๐ŸŽฏ WHAT IS IT USED FOR?

Resolving duplicate event deliveries from Kafka/Kinesis and reconstructing current entity state.

๐Ÿ’ป EXAMPLE
from pyspark.sql.window import Window
from pyspark.sql.functions import col, row_number

dedup_window = Window.partitionBy("order_id").orderBy(col("updated_at").desc())
deduped_df = raw_orders \
    .withColumn("rn", row_number().over(dedup_window)) \
    .filter(col("rn") == 1) \
    .drop("rn")

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Natural Key Deduplication with Window row_number().

  • โœ“ Define deduplication window by natural key
  • โœ“ Assign row numbers ordered by latest timestamp
  • โœ“ Filter rank 1 to preserve latest state