The situation
dim_customer holds the history of each customer's city as a type 2 slowly changing
dimension. Every night a batch of changes arrives from the CRM and has to be applied
to it.
The batch is what the CRM saw, not what the dimension needs. It contains saves that changed nothing, several changes for the same customer, customers the dimension has never seen, and changes that reached the feed weeks late.
Input tables
dim_customer
The dimension before the batch. One row per version of a customer's city.
| Column | Type | Description |
|---|---|---|
customer_id |
BIGINT | The customer. |
city |
STRING | The city during this version. Never NULL. |
valid_from |
DATE | First day of the version. |
valid_to |
DATE | The day the next version started. NULL for the current version. |
is_current |
BOOLEAN | True for the customer's latest version. |
The table is well formed: every customer has exactly one current row, one version ends on the day the next starts, and two consecutive versions never have the same city.
changes
The batch. One row per reported change. A customer has at most one row per date.
| Column | Type | Description |
|---|---|---|
customer_id |
BIGINT | The customer. May be new to the dimension. |
city |
STRING | The city reported. Never NULL. |
changed_on |
DATE | The date the change took effect. |
Requirement
Return the complete dimension as it should look after the batch: every existing version, updated where needed, plus the new versions.
- Late changes are ignored. For a customer already in the dimension, a change
counts only if
changed_onis after thevalid_fromof the customer's current version. A change dated on or before it is discarded. For a customer who is new to the dimension, every change counts. - Changes are applied in date order. Go through a customer's accepted changes
from the earliest
changed_onto the latest. - A change to the same city is not a change. If the reported city equals the city of the version in force at that point, nothing happens.
- A real change closes one version and opens another. The version in force gets
valid_to=changed_onandis_current= false. A new version starts withvalid_from=changed_on. - A new customer gets a first version starting at their earliest change.
- After the batch, each customer's latest version has
valid_to= NULL andis_current= true. All others haveis_current= false. - Customers with no accepted change keep their rows exactly as they are.
Expected output
One row per version, for all customers.
| Column | Type | Description |
|---|---|---|
customer_id |
BIGINT | |
city |
STRING | |
valid_from |
DATE | |
valid_to |
DATE | NULL for the current version. |
is_current |
BOOLEAN |
Explanation
Show explanationGives the answer away. Try the problem first.
The approach
The usual way to describe an SCD2 load is as a set of actions: close this row, insert that one. With several changes for one customer in a single batch, that turns into a loop, and loops are not what Spark is good at.
A simpler way to see it: every version in the dimension, and every change in the batch, is the same kind of statement, "from this date the city is X". Put all of them in one list per customer, and the versions can be rebuilt from the list in one pass.
Step 1: discard the changes that are too late. A change counts if the customer is new, or if it is dated after the start of the customer's current version.
current_from = dim.filter(F.col("is_current")).select(
"customer_id", F.col("valid_from").alias("current_from")
)
accepted = (
changes.join(current_from, on="customer_id", how="left")
.filter(F.col("current_from").isNull() | (F.col("changed_on") > F.col("current_from")))
)
Step 2: one timeline. Union the existing versions (with valid_from as the date)
and the accepted changes.
Step 3: rebuild. Order each customer's entries by date. An entry starts a version
if it is the first one, or if its city differs from the entry before it. Keep those,
and a version's valid_to is the valid_from of the next one (lead). The last
version has no next one, so its valid_to is NULL and it is the current row.
This is the method from problem 4, applied to old and new entries together. Every rule of the requirement falls out of it:
- A save with the same city is not the start of a version, so it disappears.
- Several changes for one customer are just several entries in the list.
- A customer who moves away and back gets two new versions.
- A new customer's list contains only batch entries, and the first one starts their first version.
- A customer with no accepted change has only their old entries, which rebuild to exactly the rows they had.
The dimension has 58 rows for 30 customers and the batch has 28 changes. After the batch there are 79 rows for 33 customers.
Why rebuilding is safe here
Rebuilding relies on the dimension being well formed, as the problem states: versions follow each other without gaps and consecutive versions differ. Then the old entries reproduce the old rows exactly. On a table with gaps or repeated cities this approach would silently "repair" them, which may or may not be wanted. In production, with a large dimension, you would also restrict the rebuild to the customers that appear in the batch and leave everyone else's rows untouched.
Common wrong answers
Applying late changes. Returns 82 rows. A change dated before the current version started gets inserted into the past, and the customer's history is rewritten with information that was already out of date when it arrived. Customers 923 and 925 each have one. Whether late changes should be ignored, or merged into history properly, is a business decision; here the rule is to ignore them.
>= instead of >. Returns 80 rows. Customer 924 has a change dated on the day
their current version started. Accepting it creates two entries on the same date, and
a version that starts and ends on the same day.
Treating every accepted change as a new version. Returns 83 rows. Saves that changed nothing become versions, so the dimension grows every night without any real change, and "how many times did this customer move" gives the wrong answer.
Handling only one change per customer. Returns 75 rows. Taking each customer's latest change loses the versions in between. Seven customers have two changes in this batch.
Forgetting customers who are new. Returns 75 rows. If the late-change filter is written as an inner join to the current rows, a customer who is not in the dimension yet has no current row and is filtered out.
Inserting without closing. Returns 86 rows, with two or more rows marked current
for the same customer. Any join that uses is_current now duplicates those customers.
In production: MERGE
On Delta Lake this is usually written as a MERGE INTO. A single MERGE cannot both
update the old row and insert a new one for the same key, so the standard pattern
feeds each change in twice: once with the real key (to close the current row) and
once with a NULL key (so it falls through to WHEN NOT MATCHED and is inserted). It
also needs the batch reduced to one row per customer first, which is where the
"several changes in one batch" case has to be solved anyway.
Edge cases in the data
| Case | Customer | What it catches |
|---|---|---|
| A plain change of city | 919 | The basic close-and-insert. |
| Saved again with the same city | 920 | Creating a version for a non-change. |
| Two changes in one batch | 921 | Handling only the latest change. |
| Moved away and back | 922 | Collapsing by city instead of by consecutive entries. |
| Change dated before the current version | 923 | Applying late changes. |
| Change dated on the current version's start | 924 | >= instead of >. |
| One late change and one valid change | 925 | Rejecting the customer instead of the change. |
| An unchanged save, then a real change | 926 | The no-op must not hide the change after it. |
| The same new city reported twice | 927 | Two versions with the same city in a row. |
| Not in the batch | 928 to 930 | Losing or altering untouched customers. |
| New customers, one or two changes | 931 to 933 | Inner join to current rows; collapsing for new customers too. |