Skip to main content
πŸ“˜ Complete PDF

PySpark Certification Practice Test 09

Complete Logic Questions

Question 1 of 20
πŸ“‹ Multiple Choice
Question 161
A retail enterprise receives customer profile updates from multiple source channels. Input Schema: ```text customer_id | city | update_date ``` The business requires keeping only the single latest record for each `customer_id` based on `update_date`. Which window function completes this deduplication logic?
A. min()
B. avg()
βœ“
C. row_number()
D. count()
Answer
βœ… C. row_number()
Explanation

1. Concept Overview The standard and most robust design pattern for deduplicating records by timestamp in Apache Spark is applying the **`row_number()` window function**. By partitioning the dataset by the business entity key (`customer_id`), ordering the records within each partition by the timestamp descending (`update_date.desc()`), and filtering for `row_number == 1`, the pipeline deterministically isolates the single most recent record per customer.

2. Architecture & Design Principle 1. **Window-Based Deduplication vs. GroupBy**: - Using `groupBy("customer_id").agg(max("update_date"))` only returns the key and the latest timestamp; it drops all other non-aggregate payload columns (like `city`) unless complex struct aggregations are used. - `row_number()` over `Window.partitionBy("customer_id").orderBy(col("update_date").desc())` preserves the entire schema, attaching an integer rank to each row. 2. **Deterministic Partitioning**: Spark shuffles rows with identical `customer_id` to the same partition, sorts them in-memory by `update_date` descending, and assigns `1` to the newest record.

3. Step-by-Step Code / Logic Execution 1. Construct the window specification:

   from pyspark.sql.functions import col, row_number
   from pyspark.sql.window import Window

   window_spec = Window.partitionBy("customer_id").orderBy(col("update_date").desc())

2. Apply the window function and filter:

   latest_customers = (
       df.withColumn("rn", row_number().over(window_spec))
         .filter(col("rn") == 1)
         .drop("rn")
   )

3. Execution trace: - For customer C101 with updates on '2026-01-01' and '2026-01-15': - '2026-01-15' receives rn = 1 (retained). - '2026-01-01' receives rn = 2 (filtered out).

4. Why the Correct Answer Is Optimal Option C is correct because: - `row_number()` guarantees a unique integer for each record, preventing duplicate rows even when two updates share identical timestamps. - Filtering on `rn == 1` guarantees exactly one record per customer entity.

5. Why Alternative Options Fail - Option A (min()): Incorrect; `min()` computes the minimum scalar value, not a row ranking index. - Option B (avg()): Incorrect; `avg()` computes an arithmetic mean. - Option D (count()): Incorrect; `count()` calculates row totals, not relative sequential ordering.

6. Edge Cases & Production Pitfalls - **Tied Timestamps**: If two updates for the same customer share the exact same millisecond timestamp, `row_number()` arbitrarily picks one unless a secondary sort key is added: `orderBy(col("update_date").desc(), col("ingestion_id").desc())`. - **Global Memory Overhead**: If a single customer has 10 million updates, that entire partition must fit into executor memory during window evaluation.

7. Performance & Optimization Considerations - In Spark 3.0+, Catalyst optimizes window row-number filters by performing **window rank pushdown**, discarding rows with rank > 1 early in the physical plan.

8. Reliability & Operational Best Practices - Always drop the temporary ranking column (`.drop("rn")`) before persisting to production tables to maintain schema cleanliness.

9. Real-World Architectural Scenario A financial CRM consolidates customer address updates from mobile apps, call centers, and branch visits. Using `row_number()` partitioned by `customer_id` ordered by `update_timestamp.desc()` ensures that marketing communications are dispatched to the customer's verified latest address.

10. Official Documentation & Learning Resources - Window Deduplication: [PySpark DataFrame Window Functions Tutorial](/tutorials/pyspark/df-window-functions)

Answered: 0 / 20
Question Navigator (Test 09)0% Answered