File size: 1,983 Bytes
e8c001c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
---
id: online-compute_FlinkSQL_flinksql_012
name: Session Window User Behavior Statistics
category: online-compute/FlinkSQL
timeout_seconds: 600
modality: pure-text
engine: flink-sql
---
## Prompt
I need you to write a Flink SQL that uses the built-in datagen connector to simulate a user behavior data source, computes per-user behavioral statistics over a 30-minute session window (`SESSION`), and outputs the results to the console.

**Business Background and Objective**: Simulate a user behavior stream using a datagen built-in table. Group by a 30-minute session window to compute the total action count (`COUNT`) and the number of distinct action types (`COUNT DISTINCT`) per user within each session window. Output the results to the console.

**Source Table Definition**:
- `user_actions` (user behavior stream, datagen connector):
  - `user_id INT`: User ID, randomly generated in the range 1–5000
  - `action_id INT`: Action type ID, randomly generated in the range 1–10
  - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds
  - Generation rate: `rows-per-second = 2000`

**Output Table Definition**:
- `console_output` (print connector):
  - `user_id INT`: User ID
  - `session_start TIMESTAMP(3)`: Session window start time
  - `session_end TIMESTAMP(3)`: Session window end time
  - `action_count BIGINT`: Total action count
  - `unique_actions BIGINT`: Number of distinct action types

**SQL Logic**:
- Apply `SESSION(event_time, INTERVAL '30' MINUTE)` session window on `user_actions`
- Group by `SESSION(event_time, INTERVAL '30' MINUTE)` and `user_id`
- Aggregate `COUNT(*) AS action_count` and `COUNT(DISTINCT action_id) AS unique_actions`
- Use `SESSION_START` and `SESSION_END` functions to obtain the window start and end times

**Output Requirements**:
- Use `INSERT INTO console_output` to output the results.
- Output field order: `user_id`, `session_start`, `session_end`, `action_count`, `unique_actions`