Skip to content

73. Live Page View Counts

Difficulty: Easy · Topics: Streaming, Aggregations

Page views arrive as a stream views (page, ts). A live dashboard keeps a running total of views per page since the stream started.

The dashboard only wants what changed: after each micro-batch, write the current total of every page that got new views in that batch, and nothing for pages that did not. Return page, views, and start the query with the output mode that does this.

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

views

batchpagets
1home2024-05-01 10:00:00
1home2024-05-01 10:01:00
1pricing2024-05-01 10:02:00
2home2024-05-01 10:05:00
2docs2024-05-01 10:06:00
3pricing2024-05-01 10:09:00
3pricing2024-05-01 10:10:00

Expected output

batchpageviews
1home2
1pricing1
2home3
2docs1
3pricing3

Hints

Hint 1Count per page with groupBy("page").count(), then rename the count to views.
Hint 2There are three output modes: complete writes the whole result table after every batch, update writes only the rows that changed, and append writes rows that will never change again.
Hint 3Start the query: result.writeStream.outputMode("…").start(). Append mode is refused for an aggregation without a watermark, because a running total can always change.

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