Sessionization
Pattern. Assign events to sessions: a new session starts when the gap since the previous event exceeds a threshold. Pure SQL, per batch, with window functions.
The query
Gap threshold: 3,000 ms.
SELECT user, session, min(ts) AS session_start, max(ts) AS session_end, count(*) AS events
FROM (
SELECT user, ts,
sum(CASE WHEN gap IS NULL OR gap > 3000 THEN 1 ELSE 0 END)
OVER (PARTITION BY user ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session
FROM (
SELECT user, ts, ts - lag(ts) OVER (PARTITION BY user ORDER BY ts) AS gap
FROM flow
) gapped
) sessionized
GROUP BY user, session
How it works:
lag(ts)computes the gap to the previous event per user.- The running
sumof "gap exceeded" markers gives each event a monotonically increasing session number. GROUP BY user, sessioncollapses each session into one row.
Input and output
Input (session gap 3000 ms):
| user | action | ts |
|---|---|---|
| a | view | 1000 |
| a | click | 1100 |
| a | buy | 5100 |
Output:
| user | session | session_start | session_end | events |
|---|---|---|---|---|
| a | 1 | 1000 | 1100 | 2 |
| a | 2 | 5100 | 5100 | 1 |
Runnable example
examples/sql_sessionization.yaml
(manifest name sql-sessionization).
Boundaries
- Per-batch scope. A session split across two batches becomes two sessions. For streaming sessions with state, use a Job with event time, or the session window buffer (processing time).
- Timestamps here are plain Int64 milliseconds; to use event-time windows instead, declare them on the Job source (see event time and watermarks).