Sessionize Events
EasySorting · Databricks
You are given clickstream events as [user_id, timestamp] pairs in no particular order, and an inactivity limit gap.
For each user, sort their events by time and split them into sessions: an event stays in the current session if it happens at most gap time units after that user's previous event; otherwise it starts a new session. (Events at the same timestamp are 0 apart.)
Return every session as [user_id, start, end, event_count], where start and end are the first and last timestamps in the session. Sort the result by user_id (normal string order), then by start.
Example 1
- Input:
- events = [["u2", 40], ["u1", 1], ["u1", 3], ["u2", 30], ["u1", 10], ["u1", 12]], gap = 5
- Output:
- [["u1", 1, 3, 2], ["u1", 10, 12, 2], ["u2", 30, 30, 1], ["u2", 40, 40, 1]]
- Explanation
- u1's events sorted are 1, 3, 10, 12. The gap 3 -> 10 is 7, more than 5, so u1 has two sessions: [1, 3] and [10, 12], each with 2 events. u2's events 30 and 40 are 10 apart, giving two single-event sessions.
Example 2
- Input:
- events = [["a", 5], ["a", 5], ["a", 8]], gap = 3
- Output:
- [["a", 5, 8, 3]]
- Explanation
- Two events at the same time are 0 apart. The next is exactly 3 later, which is still within the gap, so all three form one session from 5 to 8.
Example 3
- Input:
- events = [], gap = 10
- Output:
- []
- Explanation
- No events means no sessions.
Constraints
0 <= events.length <= 10^50 <= timestamp <= 10^90 <= gap <= 10^9user_idis a non-empty string