Skip to content

78. Trending Searches in Sliding Windows

Difficulty: Hard · Topics: Streaming, Aggregations, Filtering & Selection

Searches arrive as a stream searches (term, ts). A term is trending in a window when it was searched at least 2 times in it.

Use 10-minute windows that start every 5 minutes (so every search counts in two windows), with a 5-minute watermark on ts. Write each trending (window, term) exactly once, when its window is final. Return window_start, window_end, term, searches.

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

searches

batchtermts
1spark2024-05-01 10:01:00
1spark2024-05-01 10:04:00
1dbt2024-05-01 10:06:00
1spark2024-05-01 10:07:00
2dbt2024-05-01 10:08:00
2spark2024-05-01 10:12:00
3dbt2024-05-01 10:30:00

Expected output

batchwindow_startwindow_endtermsearches
22024-05-01 09:55:002024-05-01 10:05:00spark2
32024-05-01 10:00:002024-05-01 10:10:00spark3
32024-05-01 10:00:002024-05-01 10:10:00dbt2
32024-05-01 10:05:002024-05-01 10:15:00dbt2
32024-05-01 10:05:002024-05-01 10:15:00spark2

Hints

Hint 1A sliding window takes a third argument, the slide: F.window("ts", "10 minutes", "5 minutes"). A search at 10:07 falls in [10:00, 10:10) and [10:05, 10:15).
Hint 2Filter after the aggregation: .filter(F.col("searches") >= 2). A filter keeps no state, so it is fine in append mode.
Hint 3Written once when final is append mode, which needs the watermark before the groupBy.

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