Datasets:
id: online-compute_FlinkSQL_flinksql_008
name: Session Window User Behavior Aggregation
category: online-compute/FlinkSQL
timeout_seconds: 600
modality: pure-text
engine: flink-sql
Prompt
I need you to write a Flink SQL that uses a datagen built-in table to simulate a user behavior stream, performs session window aggregation to compute behavioral metrics per user within each session, and outputs the results to the console.
Business Background and Objective: Simulate a user behavior data stream using a datagen built-in table that generates 50 records per second, containing four fields: userId (user ID, string of length 6), action (action type, string of length 8), action_time (action occurrence time, timestamp), and ftime (event time, timestamp). Based on this datagen table, using ftime as the event time (with a 5-second watermark delay), perform a 30-minute session window (SESSION) aggregation grouped by userId. Compute the following metrics for each user within each session window: session start time, session end time, total action count, number of distinct action types, and the last action time (the maximum value of action_time). Output the results to a built-in console table.
Source Table Definition:
user_source(user behavior stream, datagen connector):userId VARCHAR: User ID, randomly generated, 6 characters in lengthaction VARCHAR: Action type, randomly generated, 8 characters in lengthaction_time TIMESTAMP(3): Action occurrence timeftime: UsesLOCALTIMESTAMPto generate event time, with a WATERMARK delay of 5 seconds- Generation rate:
rows-per-second = 50
Output Table Definition:
console_output(print connector):user_id VARCHAR: User IDsession_start TIMESTAMP: Session start timesession_end TIMESTAMP: Session end timeaction_count BIGINT: Total action countunique_actions BIGINT: Number of distinct action typeslast_action_time TIMESTAMP: Last action time
Query Logic:
- Window:
SESSION(ftime, INTERVAL '30' MINUTE)session window - Grouping: Group by
userIdand the session window - Aggregation:
COUNT(*)for total action count,COUNT(DISTINCT action)for distinct action type count,MAX(action_time)for last action time - Window functions: Use
SESSION_START/SESSION_ENDto obtain the window start and end times
Output Requirements:
- Use
INSERT INTO console_outputto output the results. - Output field order:
user_id,session_start,session_end,action_count,unique_actions,last_action_time