Skip to content

66. Net Changes from a Change Feed

Difficulty: Hard · Topics: Aggregations, Conditional Logic, Filtering & Selection

feed is a Delta Change Data Feed for a range of versions: id, value, change_type ('insert', 'update_preimage', 'update_postimage', 'delete') and commit_version. An id changes at most once per version.

Downstream only needs the net effect of the whole range. Return one row per id with id, net_change and value:

Ids that were inserted and then deleted within the range never existed downstream: leave them out.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

feed

idvaluechange_typecommit_version
1aupdate_preimage5
1bupdate_postimage5
2xinsert5
2xupdate_preimage6
2yupdate_postimage6
3qdelete6
4minsert6
4mdelete7

Expected output

idnet_changevalue
1updatedb
2insertedy
3deletednull

Hints

Hint 1update_preimage rows describe the old value and are not needed: drop them so each version has one row per id.
Hint 2Per id, min_by("change_type", "commit_version") is the first change and max_by(...) the last; max_by("value", ...) is the final value.
Hint 3Build net_change with when, then filter out the insert-then-delete case.

Learn the concepts

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · Learn · All problems