Skip to content

74. Enrich a Stream of Orders with Customer Data

Difficulty: Easy · Topics: Streaming, Joins, Filtering & Selection

Orders arrive as a stream orders (order_id, customer_id, amount, ts). customers (customer_id, country, tier) is an ordinary, static DataFrame.

For every order with a positive amount (the shop sends test orders with an amount of 0 or less), write order_id, customer_id, amount, country, tier as soon as it arrives. A new customer may not be in customers yet: keep their orders, with country and tier null.

The stream arrives in micro-batches: batch in the preview is the batch an event arrives in, not a column of the stream. The expected output lists every row your query writes, with batch set to the micro-batch after which it is written.

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

Sample data

orders

batchorder_idcustomer_idamountts
110114992024-05-01 10:00:00
11023120.52024-05-01 10:01:00
21032-12024-05-01 10:02:00
21044752024-05-01 10:03:00
31051202024-05-01 10:05:00

customers

customer_idcountrytier
1INgold
2USsilver
3DEsilver

Expected output

batchorder_idcustomer_idamountcountrytier
11011499INgold
11023120.5DEsilver
2104475nullnull
3105120INgold

Hints

Hint 1A stream can be joined to a static DataFrame like any other join: each micro-batch is joined to the whole static table.
Hint 2An inner join drops the orders of customers not in customers; keep them with a "left" join.
Hint 3A filter and a join keep no state, so append mode writes each order once, in the batch it arrives in.

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 · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance

Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice