Antonio Feregrino
01/13/2025, 9:32 AMuser_id, date, event_name and are stored in a table named `user_events`:
CREATE TABLE IF NOT EXISTS user_events (
`user_id` STRING,
`event` STRING,
`date` TIMESTAMP(3) NOT NULL,
WATERMARK FOR `date` AS `date`
);
My goal is to perform aggregations over a 30-minute window and achieve low (hopefully, sub-second latency) for updates. I've considered two approaches:
Approach 1: Windowed Aggregation
SELECT
`user_id`,
window_start,
window_end,
COUNT(CASE WHEN `event` = 'page_view' THEN 1 END) AS page_view_count,
COUNT(CASE WHEN `event` = 'page_closed' THEN 1 END) AS purchase_count
FROM TABLE(HOP(
TABLE user_events,
DESCRIPTOR(`date`),
INTERVAL '5' MINUTE,
INTERVAL '30' MINUTE
))
GROUP BY `user_id`, window_start, window_end;
Approach 2: Windowing with OVER clause
SELECT
`user_id`,
`date`,
COUNT(CASE WHEN `event` = 'page_view' THEN 1 END) OVER (
PARTITION BY `user_id`
ORDER BY `date`
RANGE BETWEEN INTERVAL '30' MINUTE PRECEDING AND CURRENT ROW
) AS page_view_count,
COUNT(CASE WHEN `event` = 'page_closed' THEN 1 END) OVER (
PARTITION BY `user_id`
ORDER BY `date`
RANGE BETWEEN INTERVAL '30' MINUTE PRECEDING AND CURRENT ROW
) AS purchase_count
FROM user_events;
Approach 1 doesn't meet my latency requirements since the fixed windows emit data at set intervals and this does not align well with user behaviour. Approach 2 seems more suitable for real-time updates, but I suspect it might be less performant.
Which of these approaches is likely to be more efficient in terms of resource usage? Are there any other advantages or disadvantages to consider?
Any insights would be greatly appreciated!
(I have posted the same question on Stack Overflow, if you prefer to answer there)