35. One golden record from three systems

PySparkHardNULL trap

master data · survivorship · deduplication · window functions · first ignore nulls

Open in Colab
How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Three systems each keep their own copy of a customer: the CRM, billing and the support desk. Marketing wants one row per customer with the best email, phone and city the company knows.

The current job keeps the most trusted record of each customer and drops the rest. The CRM record usually wins, and the CRM often has no phone number. Billing had one. It was thrown away with the rest of the billing record.

Input tables

customer_records

One row per record of a customer in one system. A system can hold several records for the same customer, saved at different times.

Column Type Description
customer_id BIGINT The customer. Never NULL.
source STRING crm, billing or support.
email STRING NULL if this record has none.
phone STRING NULL if this record has none.
city STRING NULL if this record has none.
updated_at TIMESTAMP_NTZ When this record was last saved.

A customer never has two records with the same updated_at.

Requirement

Return one row per customer.

Rank a customer's records by trust:

  1. By source: crm first, then billing, then support.
  2. Within the same source, the record with the later updated_at first.

Each of email, phone and city is decided on its own: take the value from the highest-ranked record in which that column is not NULL. The three values of one customer can come from three different records.

If no record of the customer has a value for a column, that column is NULL.

Expected output

One row per customer.

Column Type Description
customer_id BIGINT
email STRING
phone STRING
city STRING

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

The usual deduplication pattern is "rank the rows, keep rank 1". It answers the question which row is best. This problem asks a different question, three times: which value is best for this column. The best email and the best phone number can sit in different rows.

So rank the rows once, and let each column look down the ranking on its own until it finds a value:

trust = F.when(F.col("source") == "crm", 1).when(F.col("source") == "billing", 2).otherwise(3)

best_first = (
    Window.partitionBy("customer_id")
    .orderBy(trust, F.col("updated_at").desc())
    .rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
)

F.first("email", ignorenulls=True).over(best_first)

Three details carry the solution:

  • ignorenulls=True. Without it, first returns the value of the first row, NULL or not, and you are back to "keep the best row".
  • The frame. A window with an orderBy has a default frame that ends at the current row. first(..., ignorenulls=True) over that frame only sees the rows ranked above the current one, so different rows of one customer get different answers. The frame has to cover the whole partition.
  • The trust order is written out. crm, billing, support is a business ranking, not an alphabetical one, so it is turned into 1, 2, 3 explicitly.

After that every row of a customer carries the same three values, and distinct() leaves one row per customer. If no record has a value for a column, first finds nothing and returns NULL.

There are 122 records for 45 customers. For 24 of them the golden record combines values from more than one record.

Common wrong answers

Keeping the best row. row_number() == 1 over the same ordering, then select the three columns. This is the job from the story. It is wrong for 24 of the 45 customers. The best rows have 18 missing emails, 20 missing phone numbers and 12 missing cities; the golden records have 6, 7 and 4. Every one of those gaps was filled in some other record that got thrown away.

F.first(column) without ignorenulls. The same result as keeping the best row, with more code. Wrong for the same 24 customers.

The default frame. Leaving out rowsBetween gives 74 rows instead of 45. A customer whose top record has no phone gets one row with a NULL phone (from the top record's point of view) and another with the phone filled in (from the second record's point of view), and distinct() keeps both.

Latest record wins, whatever the source. Ordering by updated_at alone. Wrong for 18 customers. Customer 43's support record is the newest by months; the CRM values still win, because the CRM is the more trusted system.

Ordering by source as text. Alphabetically it is billing, crm, support, so billing beats the CRM. Wrong for 19 customers.

The right sources, but the oldest record first. Forgetting .desc() on updated_at. Wrong for 13 customers.

F.max(column) per customer. Returns the alphabetically last email and the highest phone number. It always returns a value when one exists, so the result looks complete. Wrong for 25 customers.

groupBy("customer_id").agg(F.first("email", ignorenulls=True)) after an orderBy. A groupBy does not promise to see rows in the order of an earlier sort. It may work on a small table and stop working when the data is spread over more partitions. Ordering that matters belongs in a window.

Another correct way

Do it one column at a time: filter to the records where the column is not NULL, keep the top-ranked record per customer with row_number, and left join the three results to the list of customers. It gives the same answer as the reference solution. The joins have to be left joins: with inner joins, a customer with no phone number anywhere drops out, and the result has 33 rows.

In SQL the window version is FIRST_VALUE(email) IGNORE NULLS OVER (...), with the same full frame.

Keep track of where a value came from

Marketing will ask "why does this customer have this phone number?". A golden record is much easier to defend if it also stores which source and which updated_at each value came from. That is the same window with F.first(F.when(F.col("phone").isNotNull(), F.col("source")), ignorenulls=True). The problem does not ask for it. A real pipeline should.

Edge cases in the data

Customer Records Expected
41 CRM has no email; billing has one Email from billing, phone and city from the CRM.
42 Latest CRM record has no phone; an older CRM record has one The older CRM phone, not billing's. Email and city from the latest CRM record.
43 Support record is the newest All three values from the CRM.
44 Nobody has a phone; only billing has a city Phone NULL, city from billing, email from the CRM.
45 Only a support record Its values as they are; phone NULL.