-- 提取页面名称和停留时长
SELECT
event_id,
json_extract_string(PARSE_JSON(payload), '$.page') as page_name,
json_extract_int(PARSE_JSON(payload), '$.duration') as duration_sec
FROM user_events
WHERE event_type = 'page_view';
结果说明:
event_id
page_name
duration_sec
1
home
30
路径语法
$.field
$.field
:提取根级别字段
$.parent.child
$.parent.child
:提取嵌套字段
$.array[0]
$.array[0]
:提取数组指定索引元素
提取嵌套对象
当需要提取整个子对象或数组时,使用
json_extract
json_extract
,返回
JSON
JSON
类型。
-- 提取购买详情(嵌套对象)
SELECT
event_id,
json_extract(PARSE_JSON(payload), '$.details') as item_details
FROM user_events
WHERE event_type = 'purchase';
结果说明:
event_id
item_details
2
{"color":"silver","warranty":2}
提取后可继续使用
json_extract_string
json_extract_string
进一步解析:
-- 提取嵌套字段
SELECT
event_id,
json_extract_string(json_extract(PARSE_JSON(payload), '$.details'), '$.color') as color
FROM user_events
WHERE event_type = 'purchase';
结果说明:
event_id
color
2
silver
JSON 展开为行
将 JSON 数组展开为多行,常用于标签、属性列表等场景。Lakehouse 中推荐使用
EXPLODE
EXPLODE
配合类型转换。
-- 展开标签数组
SELECT
event_id,
user_id,
tag
FROM user_events,
EXPLODE(CAST(json_extract(PARSE_JSON(payload), '$.tags') AS ARRAY<STRING>)) AS t(tag)
WHERE event_type = 'page_view';
结果说明:
event_id
user_id
tag
1
101
tech
1
101
news
注意:
json_array_elements
json_array_elements
仅适用于 JSON 数组。如果字段不是数组,该函数会返回空或报错。
构建 JSON 对象
将查询结果或结构体转换为 JSON 字符串,常用于 API 响应或数据导出。
-- 将行数据转为 JSON
SELECT
event_id,
TO_JSON(NAMED_STRUCT(
'user_id', user_id,
'event_type', event_type,
'timestamp', CURRENT_TIMESTAMP()
)) as event_json
FROM user_events
WHERE event_id = 1;