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

Does BigQuery support Analytic User-Defined Functions?

BigQuery 支持:

  1. User Defined Functions (UDF) 在 SQL 和 JavaScript.
  2. Analytic functions that compute values over a group of rows and return a single result for each row. These functions can be used with 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
)

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

Query error: Function mydataset.mylen does not support an OVER clause at [16:3]

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

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

答案 reader 的一点上下文,BigQuery 不支持用户定义的 aggregate/analytical 函数,因此模拟它的一种方法是编写一个标量 UDF,接受一个数组作为输入。然后在查询中,array_agg() 函数用于将数据打包为 UDF 的输入,(这是问题中缺少的步骤)。

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

=>

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