Ole*_*hyn 3 analytic-functions google-bigquery bigquery-udf
BigQuery 支持:
问题#1:“BigQuery 是否支持分析用户定义函数?”
其背后的动机是我想实现Python pandas 代码中常见的拆分-应用-组合模式。这对于组内标准化和使用组统计数据的其他转换很有用。
我在Standart SQL中做了一个小测试:
create or replace function `mydataset.mylen`(arr array<string>) returns int64 as (
array_length(arr)
);
WITH Produce AS
(SELECT 'kale' as item, 23 as purchases, 'vegetable' as category
UNION ALL SELECT 'orange', 2, 'fruit'
UNION ALL SELECT 'cabbage', 9, 'vegetable'
UNION ALL SELECT 'apple', 8, 'fruit'
UNION ALL SELECT 'leek', 2, 'vegetable'
UNION ALL SELECT 'lettuce', 10, 'vegetable')
SELECT
item,
purchases,
category,
`mydataset.mylen`(item) over (mywindow) as windowlen
FROM Produce
window mywindow as (
partition by category
)
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我得到:
查询错误:函数 mydataset.mylen 不支持 [16:3] 处的 OVER 子句
因此,如果 BigQuery 确实支持分析 UDF,则问题 #2:“如何实现 UDF 以使其支持 OVER 子句?”
你已经非常接近解决问题了:)
为答案的读者提供一些上下文,BigQuery 不支持用户定义的聚合/分析函数,因此模拟它的一种方法是编写一个接受数组作为输入的标量 UDF。然后在查询中,使用 array_agg() 函数将数据打包为 UDF 的输入(这是问题中缺少的步骤)。
`mydataset.mylen`(item) over (mywindow) as windowlen
=>
`mydataset.mylen`(array_agg(item) over (mywindow)) as windowlen
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1060 次 |
最近记录: |