MaxCompute user-defined functions
RecTemplate provides custom MaxCompute functions (UDF, UDAF, and UDTF) for feature engineering, such as CTR calculation, sequence enrichment, and categorical aggregation.
User-defined functions
Scalar functions
|
No. |
Function name |
Function class |
Description |
|
1 |
|
|
Buckets a numeric field and returns the index of the containing interval. |
|
2 |
|
|
Combines multiple tag or category fields to generate combined tags as a Cartesian product. |
|
3 |
|
|
Parses geolocation information (country, province, and city) from an IP address. |
|
4 |
|
|
Calculates the click-through rate (CTR) as a numeric value and supports Wilson confidence interval correction. |
|
5 |
|
|
Calculates the CTR as key-value pairs and supports Wilson confidence interval correction. |
|
6 |
|
|
Calculates the CTR for MAP-type inputs. This function is the same as CTRKV. |
|
7 |
|
|
Converts a MAP type to a key-value formatted string. |
|
8 |
|
|
Enriches a single sequence, supporting deduplication and attribute processing. |
|
9 |
|
|
Enriches a real-time sequence with a historical sequence, supporting deduplication and timestamp processing. |
|
10 |
|
|
Concatenates two sequence features and caps the final length. |
Aggregate functions
|
No. |
Function name |
Function class |
Description |
|
1 |
|
|
Aggregates categorical features, supporting methods such as |
|
2 |
|
|
Performs key-value aggregation on categorical features and returns the Top-K results as a MAP. |
|
3 |
|
|
Counts key-value pairs for categorical features by event type and supports Top-K filtering. |
|
4 |
|
|
Generates the most recent sequence features (Top-K) by sorting based on timestamp. |
Table functions
|
No. |
Function name |
Function class |
Description |
|
1 |
|
|
Generates real-time sequence features from user behavior logs. |
|
2 |
|
|
Similar to |
|
3 |
|
|
Calculates message delay based on event time and sliding window configuration. |
|
4 |
|
|
Computes statistics for a user's real-time behavioral features over a sliding window. |
|
5 |
|
|
Splits a sequence array into multiple rows, each containing a reverse-order index, the element value, and the column name. |
UDFs (scalar functions)
1. Bound_Index
Function Class: bound_index.BoundIndex
Description: Buckets a numeric field and returns the index of the containing interval. Commonly used for feature discretization.
Parameters
|
Parameter |
Type |
Required |
Description |
|
field |
DOUBLE |
Yes |
The numeric field to bucket. |
|
boundaries |
ARRAY |
Yes |
An array of boundary points, for example, |
Returns
|
Output |
Type |
Description |
|
index |
BIGINT |
The index of the interval that contains the value. If |
Example
-- Register the function
CREATE FUNCTION bound_index AS 'bound_index.BoundIndex' USING 'bound_index.py';
-- Example: Bucket scores into intervals [0, 60), [60, 70), [70, 80), [80, 90), and [90, +∞)
SELECT bound_index(score, ARRAY(60.0, 70.0, 80.0, 90.0)) AS grade_level
FROM student_table;
-- score=55 returns 0, score=65 returns 1, score=85 returns 3, score=95 returns 4
2. Tag_Combo
Function Class: tag_combo.TagCombo
Description: Combines multiple tag or category fields to produce a Cartesian product of the tags.
Parameters
|
Parameter |
Type |
Required |
Description |
|
tag_fields... |
Any (variadic) |
Yes |
Multiple tag or category fields. Each field can contain multiple tags separated by |
Returns
|
Output |
Type |
Description |
|
combo_tags |
STRING |
A string of combined tags. Underscores ( |
Example
-- Register the function
CREATE FUNCTION tag_combo AS 'tag_combo.TagCombo' USING 'tag_combo.py';
-- Combine multiple tags
SELECT tag_combo(category, brand, style) AS combo_result
FROM item_table;
-- Input: category="Apparel\x1dFootwear", brand="Nike\x1dAdidas"
-- Output: "Apparel_Nike\x1dApparel_Adidas\x1dFootwear_Nike\x1dFootwear_Adidas"
3. AnalysisIP
Function Class: com.aliyun.pai.udf.AnalysisIP
Description: Parses an IP address to determine its geolocation (country, region, and city) by using the IPIP offline IP database (ipipfree.ipdb).
Parameters
|
Parameter |
Type |
Required |
Description |
|
|
String |
Yes |
The IP address to parse, such as |
|
|
String |
Yes |
The location component to retrieve. Valid values are |
Returns
|
Return type |
Description |
|
String |
The geographic name corresponding to the specified |
Example
SELECT AnalysisIP('114.114.114.114', 'country') AS country,
AnalysisIP('114.114.114.114', 'region') AS province,
AnalysisIP('114.114.114.114', 'city') AS city
FROM dual;
Notes
-
You must register the resource file
ipipfree.ipdbin MaxCompute.
4. CTR_NUM
Function Class: ctr_num.CTRNum
Description: Calculates CTR from numeric inputs. Supports Wilson score interval correction.
Parameters
|
Parameter |
Type |
Required |
Description |
|
clicks |
DOUBLE |
Yes |
The number of clicks. |
|
impressions |
DOUBLE |
Yes |
The number of impressions. |
|
is_wilson |
BOOLEAN |
No |
Specifies whether to apply the Wilson score interval. If omitted, this parameter defaults to |
Returns
|
Output |
Type |
Description |
|
ctr |
DOUBLE |
The CTR value, in the range [0, 1]. |
Example
-- Register the function
CREATE FUNCTION ctr_num AS 'ctr_num.CTRNum' USING 'ctr_num.py';
-- Calculate the CTR for each item
SELECT item_id,
ctr_num(click_count, impression_count, true) AS ctr
FROM item_stats_table
ORDER BY ctr DESC;
5. CTR_KV
Function Class: ctr_kv.CTRKV
Description: Calculates CTR from key-value formatted strings. Supports Wilson score interval correction for robust estimates with small sample sizes.
Parameters
|
Parameter |
Type |
Required |
Description |
|
clicks |
STRING |
Yes |
A string of click counts in key-value format, such as |
|
impressions |
STRING |
Yes |
The number of impressions, in the same format as |
|
is_wilson |
BOOLEAN |
No |
Specifies whether to apply the Wilson score interval. Defaults to |
Returns
|
Output |
Type |
Description |
|
ctr_kv |
STRING |
A key-value string of CTRs, sorted in descending order by CTR value. Format: |
Example
-- Register the function
CREATE FUNCTION ctr_kv AS 'ctr_kv.CTRKV' USING 'ctr_kv.py';
-- Calculate the CTR for each item
SELECT ctr_kv(clicks_str, impressions_str, true) AS ctr_result
FROM item_stats_table;
-- Example output: item1:0.152341\x1ditem2:0.098234\x1ditem3:0.075612
6. CTR_KV_MAP
Function Class: ctr_kv_map.CTRKVMap
Description: Calculates CTR from MAP inputs. Equivalent to CTR_KV, but operates on MAP inputs and returns a MAP output.
Parameters
|
Parameter |
Type |
Required |
Description |
|
clicks |
MAP<STRING, FLOAT> |
Yes |
A MAP of clicks. |
|
impressions |
MAP<STRING, FLOAT> |
Yes |
A MAP of impressions. |
|
is_wilson |
BOOLEAN |
No |
Specifies whether to apply the Wilson score interval. Defaults to |
Returns
|
Output |
Type |
Description |
|
ctr_map |
MAP<STRING, FLOAT> |
A MAP containing the calculated CTR for each key. |
Example
-- Register the function
CREATE FUNCTION ctr_kv_map AS 'ctr_kv_map.CTRKVMap' USING 'ctr_kv_map.py';
-- Calculate the CTR for each item (MAP version)
SELECT ctr_kv_map(clicks_map, impressions_map, true) AS ctr_map
FROM item_stats_table;
7. Map2Str
Function Class: map2str.Map2Str
Description: Converts a MAP to a key-value formatted string.
Parameters
|
Parameter |
Type |
Required |
Description |
|
field |
MAP<STRING, FLOAT> |
Yes |
The MAP to convert. |
Returns
|
Output |
Type |
Description |
|
kv_str |
STRING |
A key-value formatted string. Entries are separated by |
Example
-- Register the function
CREATE FUNCTION map2str AS 'map2str.Map2Str' USING 'map2str.py';
-- Convert a MAP to a string
SELECT map2str(feature_map) AS feature_str
FROM feature_table;
-- Input: {'age': 25.0, 'gender': 1.0}
-- Output: age:25.0\x1dgender:1.0
8. SINGLE_SEQ_REPLENISH
Function Class: single_seq_replenish.SingleSeqReplenish
Description: Merges a sequence with a T-1 sequence, with optional deduplication.
Parameters
|
Parameter |
Type |
Required |
Description |
|
seq1 |
STRING |
Yes |
The real-time sequence feature. |
|
re_seq |
STRING |
Yes |
The T-1 sequence feature. |
|
id1 |
STRING |
Yes |
A sequence of IDs corresponding to seq1, used for deduplication. |
|
id2 |
STRING |
Yes |
A sequence of IDs corresponding to re_seq, used for deduplication. |
|
curren_time |
Any |
No |
The timestamp of the current event. Defaults to |
|
delim |
STRING |
No |
The delimiter. Defaults to |
|
length |
BIGINT |
No |
The final sequence length. Defaults to |
|
deduplication_method |
BIGINT |
No |
The deduplication method: |
Returns
|
Output |
Type |
Description |
|
replenished_seq |
STRING |
The augmented sequence string. |
Example
-- Register the function
CREATE FUNCTION single_seq_replenish AS 'single_seq_replenish.SingleSeqReplenish' USING 'single_seq_replenish.py';
-- Augment a single sequence
SELECT user_id,
single_seq_replenish(seq1, seq2, id1, id2, event_time, ';', 50, 1) AS full_seq
FROM user_sequence_table;
9. SEQ_REPLENISH
Function Class: seq_replenish.SeqReplenish
Description: Merges a real-time sequence with a historical sequence to build a complete user behavior history. Supports deduplication and timestamp handling. Commonly used in TF pipelines.
Parameters
|
Parameter |
Type |
Required |
Description |
|
seq1 |
STRING |
Yes |
The real-time sequence feature. |
|
re_seq |
STRING |
Yes |
The T-1 sequence feature (the historical sequence for augmentation). |
|
curren_time |
Any |
Yes |
The timestamp of the current event (Unix time). |
|
delim |
STRING |
No |
The delimiter. Defaults to |
|
length |
BIGINT |
No |
The final sequence length. Defaults to |
|
deduplication_method |
BIGINT |
No |
The deduplication method: |
Returns
|
Output |
Type |
Description |
|
replenished_seq |
STRING |
The augmented sequence, deduplicated and timestamped per the specified parameters. |
Example
-- Register the function
CREATE FUNCTION seq_replenish AS 'seq_replenish.SeqReplenish' USING 'seq_replenish.py';
-- Augment a real-time sequence with a historical sequence
SELECT user_id,
seq_replenish(realtime_seq, history_seq, event_time, ';', 50, 1) AS full_seq
FROM user_sequence_table;
10. SEQ_CONCAT
Function Class: seq_concat.SeqConcat
Description: Concatenates two sequences by appending seq2 to seq1 and truncating the result to a specified length. Commonly used in TF pipelines to combine real-time and historical features.
Parameters
|
Parameter |
Type |
Required |
Description |
|
seq1 |
STRING |
Yes |
The real-time sequence feature. |
|
seq2 |
STRING |
Yes |
The T-1 sequence feature (historical feature). |
|
delim |
STRING |
No |
The delimiter. Defaults to |
|
length |
BIGINT |
No |
The final sequence length. Defaults to |
Returns
|
Output |
Type |
Description |
|
merged_seq |
STRING |
The resulting sequence, formed by appending seq2 to seq1, truncated to the specified length. |
Example
-- Register the function
CREATE FUNCTION seq_concat AS 'seq_concat.SeqConcat' USING 'seq_concat.py';
-- Concatenate real-time and historical behavior sequences
SELECT user_id,
seq_concat(realtime_seq, history_seq, ';', 100) AS full_seq
FROM user_sequence_table;
-- realtime_seq: "item1;item2;item3"
-- history_seq: "item4;item5;item6"
-- Output: "item1;item2;item3;item4;item5;item6"
UDAFs (aggregate functions)
count_kv
Class: count_kv.CountKV
Description: Aggregates categorical features using sum, max, min, or avg, with optional Top-K filtering.
Parameters
|
Parameter |
Type |
Required |
Description |
|
cate |
STRING |
Yes |
The category field. |
|
value |
DOUBLE |
Yes |
The value to aggregate. |
|
agg_type |
STRING |
Yes |
The aggregation method: |
|
top_k |
BIGINT |
No |
The maximum number of keys to retain. Default: 50. |
|
is_apply_agg |
BOOLEAN |
No |
Specifies whether to include the current row in the aggregation. Default: TRUE. |
Return value
|
Output |
Type |
Description |
|
kv_str |
STRING |
A key-value pair string, sorted in descending order by aggregated value. Items are separated by |
Examples
-- Register the function
CREATE FUNCTION count_kv AS 'count_kv.CountKV' USING 'count_kv.py';
-- Calculate the total number of clicks for each category
SELECT category,
count_kv(item_id, click_count, 'sum', 100, true) AS item_stats
FROM item_click_table
GROUP BY category;
-- Example output: "item1:150\x1ditem2:120\x1ditem3:95"
-- Calculate the average dwell time for each category
SELECT category,
count_kv(item_id, duration, 'avg', 50, true) AS avg_duration_stats
FROM item_view_table
GROUP BY category;
-- Example output: "item1:45.5\x1ditem2:32.1\x1ditem3:28.7"
count_kv_map
Function class: com.aliyun.pai.udf.CountKV
Description: Aggregates key-value statistics for categories using sum, avg, max, or min, and returns top-K results. Supports multiple categories separated by \u001D.
Parameters
|
Parameter |
Type |
Required |
Description |
|
|
STRING |
Yes |
The category field. You can specify multiple categories separated by |
|
|
FLOAT |
Yes |
The value to aggregate. |
|
|
STRING |
No |
The aggregation type. Valid values: |
|
|
INT |
No |
The number of Top-K results to retain. Default: |
|
|
BOOLEAN |
Yes |
Specifies whether to include the current row in the aggregation. If |
Return value
|
Return type |
Description |
|
Map<STRING, FLOAT> |
A map of the top-K key-value pairs, sorted by value in descending order. |
Examples
-- Calculate the top 10 product categories by click count for each user.
SELECT user_id,
count_kv_map(category, 1.0, 'sum', 10, true) AS top_categories
FROM user_behavior
GROUP BY user_id;
-- Example output: {"electronics": 15.0, "clothing": 10.0, "food": 8.0}
Notes
-
When
aggTypeis set toavg, the function maintains both a sum and a count to calculate the final average. -
The category field accepts array-like input, with items separated by the special character
\u001D(ASCII 29). -
If
topK <= 0, all categories are returned.
COUNT_CATES_KVS
Function class: count_cates_kvs.CountCatesKVS
Description: Calculates key-value statistics for categorical features by event type. Supports Top-K filtering and event-based calculation formulas.
Parameters
|
Parameter |
Type |
Required |
Description |
|
cates |
ANY |
Yes |
The category field. It can be a single value or multiple values separated by a delimiter. |
|
values |
BIGINT/DOUBLE/ARRAY |
Yes |
The value to aggregate. It can be a single value or a list. |
|
event |
STRING |
Yes |
The event field. |
|
event_types |
STRING/ARRAY |
Yes |
The event types to calculate statistics for. Multiple event types are separated by commas. |
|
event_formulas |
STRING |
No |
The event calculation formula. For example, |
|
sep |
STRING |
No |
The delimiter for multiple category values. Default: |
|
top_k |
BIGINT |
No |
The maximum number of keys to retain. Default: 50. |
|
is_punish |
BOOLEAN |
No |
When using a formula, specifies whether to penalize the denominator with the mean value. Default: FALSE. |
Return value
|
Output |
Type |
Description |
|
kv_array |
ARRAY |
An array of key-value pair strings ordered by event type and category, where each element is formatted as |
Examples
-- Register the function
CREATE FUNCTION count_cates_kvs AS 'count_cates_kvs.CountCatesKVS' USING 'count_cates_kvs.py';
-- Calculate statistics for a user's category-based behavior across different events
SELECT user_id,
count_cates_kvs(category, 1, event_type, 'click,purchase', 'purchase/click', '\x1d', 100, false) AS stats_array
FROM user_behavior_table
GROUP BY user_id;
-- Example output: ["cate1:10\x1dcate2:5", "cate1:2\x1dcate2:1"] (corresponds to statistics for 'click' and 'purchase/click' respectively)
WM_CONCAT_BY_SORT
Function class: wm_concat_by_sort.WMConcatBySort
Description: Generates a top-K sequence of recent features sorted by timestamp. Used to build user behavior sequences.
Parameters
|
Parameter |
Type |
Required |
Description |
|
values |
STRING |
Yes |
The sequence elements to concatenate. |
|
timestamp |
ANY |
Yes |
The timestamp for sorting. |
|
event |
STRING |
Yes |
The event in the current row. |
|
valid_event_selections |
STRING/ARRAY |
Yes |
A list of valid events to include in the sequence. |
|
sequence_delim |
STRING |
No |
The sequence delimiter. Default: |
|
top_k |
BIGINT |
No |
The sequence length. Default: 50. |
Return value
|
Output |
Type |
Description |
|
seq_str |
STRING |
The top-K sequence elements, sorted by timestamp in descending order and separated by the |
Examples
-- Register the function
CREATE FUNCTION wm_concat_by_sort AS 'wm_concat_by_sort.WMConcatBySort' USING 'wm_concat_by_sort.py';
-- Build a user's most recent behavior sequence
SELECT user_id,
wm_concat_by_sort(item_id, event_time, event_type, 'click,view,purchase', ';', 50) AS behavior_seq
FROM user_behavior_table
GROUP BY user_id;
-- Example output: "item50;item49;item48;...;item1" (sorted in descending order by time, with the most recent behavior first)
UDTFs (table-valued functions)
RtSeqFeature: Real-time sequence feature generation
Function class: com.aliyun.pai.udf.CountKV.RtSeqFeature
Description: Generates real-time sequence features from user behavior logs. Supports multiple event types, scenes, deduplication, length control, and time windows to prevent lookahead bias.
Parameters
|
Index |
Parameter |
Type |
Required |
Description |
|
1 |
|
String |
Yes |
User ID. |
|
2 |
|
Long (bigint) |
Yes |
Event timestamp. |
|
3 |
|
Array |
Yes |
An array of values for the sequence feature fields to record. |
|
4 |
|
Array |
Yes |
The names of the sequence feature fields, such as |
|
5 |
|
String |
Yes |
The current event type. |
|
6 |
|
Array |
Yes |
A list of valid event types, such as |
|
7 |
|
Array |
Yes |
An array of integers specifying the sequence length for each event. |
|
8 |
|
Int |
Yes |
The deduplication method. |
|
9 |
|
String |
Yes |
The sequence combination method. |
|
10 |
|
Int |
Yes |
The processing delay in seconds to prevent data lookahead. For example, a value of |
|
11 |
|
String |
Yes |
The sequence delimiter, such as |
|
12 |
|
String |
No |
The request ID, used to deduplicate output. |
|
13 |
|
String |
No |
The current scene value. |
|
14 |
|
Array |
No |
A list of valid scenes. |
Parameter notes:
-
When
args.length == 11: no requestid or scene -
When
args.length == 12: a requestid is present, but a scene is absent. -
When
args.length == 13: Therequestidis absent, andsceneis present. -
When
args.length == 14, a requestid and a scene are present.
Output
|
Return type |
Description |
|
Map<String, String> |
Contains the following key-value pairs: |
Output sequence key format:
-
If
combine_method = "all":{all}_{max_seq_len}_seq__{field_name} -
If
combine_method != "all":{event}_{seq_len}_seq__{field_name} -
If a scene is specified, the key is suffixed with
_{scene}. For example:all_10_seq_home__item_id.
Example
-- Generate real-time user behavior sequence features
SELECT output.*
FROM user_behavior
LATERAL VIEW RtSeqFeature(
user_id, -- pid
event_timestamp, -- event_time
ARRAY(item_id, category), -- fields
ARRAY("item_id", "category"), -- field_names
event_type, -- event
ARRAY("click", "add", "buy"), -- valid_events
ARRAY(10, 8, 6), -- seq_len
1, -- duplicate_method
"all", -- combine_method
300, -- pre_seconds
";", -- sequence_delim
request_id, -- request_id (optional)
scene, -- scene (optional)
ARRAY("home", "search") -- valid_scenes (optional)
) output AS feature_map;
Example output
{
"pid": "user123",
"event_time": "1709280000",
"all_10_seq__item_id": "item5;item3;item1",
"all_10_seq__category": "electronics;clothing;food",
"all_10_seq__ts": "0;120;300"
}
Notes
-
This UDTF can output one or more rows.
-
Supports output deduplication by request ID to prevent reprocessing the same request.
-
The
pre_secondsparameter prevents data lookahead by using only historical data. -
The sequence is output in reverse chronological order (newest first).
RtSeqFeature2
Function class: com.aliyun.pai.udf.CountKV.RtSeqFeature2
Description: Same as RtSeqFeature, but with different deduplication logic. When duplicate_method=2, the deduplication key for RtSeqFeature2 is fields[0] + event_time, whereas for RtSeqFeature, the key is event + fields[0] + event_time.
Parameters
Same as RtSeqFeature.
Output
Same as RtSeqFeature.
Differences from RtSeqFeature
|
Feature |
RtSeqFeature |
RtSeqFeature2 |
|
deduplication key (duplicate_method=2) |
|
|
|
deduplication key (duplicate_method=1) |
|
|
Use cases:
-
Use
RtSeqFeature2to deduplicate by item without considering the event type. -
Use
RtSeqFeatureto deduplicate by both the event type and the item.
MessageDelay
Function class: com.aliyun.pai.udf.CountKV.MessageDelay
Description: Calculates future trigger times from an event time and sliding window configuration. Creates delayed rows for cross-window statistical analysis.
Parameters
|
Index |
Parameter |
Type |
Required |
Description |
|
1 |
|
Array |
Yes |
An array of base fields to include in the output. |
|
2 |
|
Long (bigint) |
Yes |
The event timestamp. |
|
3 |
|
Array |
Yes |
A list of time windows in seconds, such as |
|
4 |
|
Boolean |
Yes |
Specifies whether to generate delayed rows. |
Output
|
Return type |
Description |
|
Array |
The output array contains the following: - All fields from the original fields - The second to last element: the window trigger timestamp ( |
Example
-- Generate delayed data rows for different time windows
SELECT output.*
FROM user_events
LATERAL VIEW MessageDelay(
ARRAY(user_id, event_type), -- fields
event_timestamp, -- event_time
ARRAY(1800, 3600, 7200), -- windows (30m, 1h, 2h)
true -- is_save
) output AS field1, field2, trigger_time, window_size;
-- If is_save=true, the function outputs one row for each window:
-- [user_id, event_type, 1709281800, 1800]
-- [user_id, event_type, 1709283600, 3600]
-- [user_id, event_type, 1709287200, 7200]
Notes
-
This function is a UDTF and may output multiple rows depending on the
is_saveparameter. -
The function automatically adds a window of
0for immediate triggering. -
This function is intended for the Mapper phase of a real-time feature MapReduce job to generate delayed rows for the Reducer.
SWCountCatesKVS
Function class: com.aliyun.pai.udf.CountKV.SWCountCatesKVS
Description: Calculates real-time user behavior statistics over sliding time windows. Supports multiple windows, event types, scenes, and Top-K category statistics for generating real-time features in batch jobs.
Parameters
|
Index |
Parameter |
Type |
Required |
Description |
|
1 |
|
String |
Yes |
User ID. |
|
2 |
|
Array |
Yes |
An array of category or tag fields, such as |
|
3 |
|
Array |
Yes |
The names of the category fields, such as |
|
4 |
|
Int |
Yes |
The value to aggregate, typically 1. |
|
5 |
|
String |
Yes |
The current event type. |
|
6 |
|
Array |
Yes |
A list of valid event types. |
|
7 |
|
Int |
Yes |
A flag indicating how to process data for the sliding window. |
|
8 |
|
Array |
Yes |
A list of time windows in seconds, such as |
|
9 |
|
Int |
Yes |
The number of Top-K items to retain for each category. |
|
10 |
|
Int |
Yes |
The number of seconds to delay processing to prevent data lookahead. |
|
11 |
|
Long (bigint) |
Yes |
The event timestamp. |
|
12 |
|
String |
Yes |
The output date in |
|
13 |
|
String |
Yes |
An identifier to categorize the output fields, such as |
|
14 |
|
String |
No |
The request ID, used to deduplicate output. |
|
15 |
|
String |
No |
The current scene value. |
|
16 |
|
Array |
No |
A list of valid scenes. |
Parameter notes:
-
When
args.length == 13: There is no requestid or scene. -
When
args.length == 14, a requestid is present, but a scene is not. -
When
args.length == 15: Therequestidis absent, but thesceneis present. -
When
args.length == 16: Arequestidand asceneare present.
Output
|
Return type |
Description |
|
Map<String, String> |
Contains the following key-value pairs: |
Output key format:
-
Window name format:
rt{X}h{Y}m{Z}s, such asrt30m,rt3h, orrt24h. -
Event count example:
user__cnt_click_rt30m. -
Category key-value pair example:
user__kv_style_id_click_rt30m. -
If a scene is specified, the scene name is added as a suffix. For example:
user__cnt_click_home_rt30m.
Category key-value pair format:
-
Separates multiple key-value pairs using the Group Separator character, which is represented as
(char)29or\u001D. -
Each key-value pair is in the format
key:value. -
Example:
"cate1:15.0\u001Dcate2:10.0\u001Dcate3:8.0".
Example
-- Generate real-time user behavior statistical features
SELECT output.*
FROM user_behavior
LATERAL VIEW SWCountCatesKVS(
user_id, -- pid
ARRAY(style_id, goods_id), -- cates
ARRAY("style_id", "goods_id"), -- cate_names
1, -- value
event_type, -- event
ARRAY("click", "add", "buy"), -- valid_events
0, -- delay_flag (0 for new data)
ARRAY(1800, 3600, 7200, 86400), -- windows (30m, 1h, 2h, 24h)
100, -- topk
5, -- pre_seconds
event_timestamp, -- event_time
"20240101", -- output_date
"user", -- side
request_id, -- request_id (optional)
scene, -- scene (optional)
ARRAY("home", "search") -- valid_scenes (optional)
) output AS feature_map;
Example output
{
"pid": "user123",
"event_time": "1709280000",
"user__cnt_click_rt30m": "15",
"user__cnt_click_rt3h": "45",
"user__cnt_add_rt30m": "8",
"user__kv_style_id_click_rt30m": "style1:10.0\u001Dstyle2:5.0",
"user__kv_goods_id_click_rt30m": "goods1:8.0\u001Dgoods2:7.0"
}
Notes
-
This function is a UDTF that outputs statistical results.
-
The
delay_flagparameter is used to implement a sliding window:-
A value of
0indicates that the data is added to all windows immediately. -
A non-
0value indicates that data for the corresponding window needs to be subtracted, which is used to maintain the sliding window.
-
-
The
pre_secondsparameter is used to prevent data lookahead. -
The
output_dateparameter controls the starting date for the output to avoid including historical data. -
Supports output deduplication by request ID.
-
The category value supports multiple tags, separated by
(char)29(that is,\u001D).
SEQ_SPLIT
Function class: seq_split.SeqSplit
Description: Splits an array of delimited strings (sequences) into multiple rows. Each row contains a reverse index (position from the end), the element value, and the corresponding column name. Use this function to flatten sequence features.
Parameters
|
Parameter |
Type |
Required |
Description |
|
seqs |
ARRAY |
Yes |
The array of delimited strings to split. |
|
col_names |
ARRAY |
Yes |
An array of column names corresponding to the |
|
sep |
STRING |
Yes |
The delimiter used within each sequence string. |
Output
|
Output column |
Type |
Description |
|
seq_len |
BIGINT |
A reverse index representing the position from the end of the sequence. |
|
item |
STRING |
The value of the sequence element. |
|
col_name |
STRING |
The corresponding column name. |
Example
-- Register the function
CREATE FUNCTION seq_split AS 'seq_split.SeqSplit' USING 'seq_split.py';
-- Split sequences into multiple rows
SELECT t.seq_len, t.item, t.col_name
FROM sequence_table
CROSS APPLY seq_split(ARRAY(seq1, seq2), ARRAY('seq1_col', 'seq2_col'), ';') AS t(seq_len, item, col_name);
-- Input: seq1="item1;item2;item3", seq2="item4;item5"
-- Output:
-- seq_len | item | col_name
-- --------|-------|----------
-- 3 | item1 | seq1_col
-- 2 | item2 | seq1_col
-- 1 | item3 | seq1_col
-- 2 | item4 | seq2_col
-- 1 | item5 | seq2_col
Function registration and usage
1. Add resource files
Add the required resource files to MaxCompute before creating functions:
-- Add a single Python file
ADD py /path/to/bound_index.py;
-- Add a JAR file
ADD jar /path/to/feature-generate-mr-v1.21.jar;
-- Add a dependent JSON configuration file (such as an FG configuration)
ADD file /path/to/fg_config.json;
2. Create functions
-- Create a UDF
CREATE FUNCTION bound_index AS 'bound_index.BoundIndex' USING 'bound_index.py';
CREATE FUNCTION ctr_num AS 'ctr_num.CTRNum' USING 'ctr_num.py';
-- Create a UDAF
CREATE FUNCTION count_kv AS 'count_kv.CountKV' USING 'count_kv.py';
-- Create a UDTF
CREATE FUNCTION seq_split AS 'seq_split.SeqSplit' USING 'seq_split.py';
3. View function list
-- List all user-defined functions
LIST FUNCTIONS;
-- View function details
DESCRIBE FUNCTION bound_index;
4. Drop a function
-- Drop the function
DROP FUNCTION bound_index;
5. Use functions
-- Use a UDF
SELECT bound_index(score, ARRAY(60.0, 70.0, 80.0, 90.0)) AS grade_level
FROM student_table;
-- Use a UDAF
SELECT category, count_kv(item_id, click_count, 'sum', 100, true) AS item_stats
FROM item_click_table
GROUP BY category;
-- Use a UDTF
SELECT t.seq_len, t.item, t.col_name
FROM sequence_table
CROSS APPLY seq_split(ARRAY(seq1), ARRAY('seq1_col'), ';') AS t(seq_len, item, col_name);
FAQ
1. Delimiters
The following delimiters are used in custom functions:
-
\x1d(Group Separator, chr(29)): Separates key-value pairs. -
;(Semicolon): Separates elements in a sequence. -
|(Pipe): Separates a time series or an FG feature. -
#(Hash): Separates sequence items and attributes.
2. Wilson confidence interval
The CTR is calculated by using the Wilson confidence interval. The formula is:
CTR = (p̂ + z²/(2n) - z * √(p̂(1-p̂)/n + z²/(4n²))) / (1 + z²/n)
Where:
-
p̂ = clicks / impressions(observed click-through rate) -
n = impressions(number of impressions) -
z = 1.96(95% confidence level)
Benefits of the Wilson confidence interval:
-
Produces robust estimates with small sample sizes.
-
Prevents extreme values (0 or 1) from distorting results.
-
Well suited for evaluating rare item performance in recommendation systems.