BigQuery 是否支持分析用户定义函数?

问题描述 投票:0回答:2

BigQuery 支持:

    SQL 和 JavaScript 中的
  1. 用户定义函数 (UDF)。
  2. 分析函数计算一组行的值并为每行返回一个结果。这些函数可以与 OVER 子句一起使用。有一组预定义的分析函数。

问题#1:“BigQuery 是否支持分析用户定义函数?”

这背后的动机是我想实现 Python pandas 代码中常见的 split-apply-combine 模式。这对于组内标准化和使用组统计数据的其他转换很有用。

我在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
)

当我运行上面的代码时,我得到:

查询错误:函数 mydataset.mylen 不支持 [16:3] 处的 OVER 子句

因此,如果 BigQuery 确实支持分析 UDF,问题 #2:“如何实现 UDF 以支持 OVER 子句?”

google-bigquery analytic-functions bigquery-udf
2个回答
5
投票

您已经非常接近解决问题了:)

为答案的读者提供一点背景信息,BigQuery 不支持用户定义的聚合/分析函数,因此模拟它的一种方法是编写一个接受数组作为输入的标量 UDF。然后在查询中,使用 array_agg() 函数将数据打包为 UDF 的输入(这是问题中缺少的步骤)。

  `mydataset.mylen`(item) over (mywindow) as windowlen

=>

  `mydataset.mylen`(array_agg(item) over (mywindow))  as windowlen

0
投票

用户定义聚合函数 (UDAF) 现已在 Google BigQuery 中提供。

这里是定义 UDAF 来计算一列数据的几何平均值的示例。

定义 UDAF:

CREATE TEMP AGGREGATE FUNCTION geometric_mean(
  column_values float64
)
RETURNS float64
AS
(
  EXP(SUM(LN(column_values))/COUNT(column_values))
);

致电 UDAF

with test_data as (
  SELECT 1 AS col1 
  UNION ALL
  SELECT 3
  UNION ALL
  SELECT 5
)
select geometric_mean(col1) from test_data;

更多信息: https://qosf.com/UDAF-in-google-bigquery.html

© www.soinside.com 2019 - 2024. All rights reserved.