在BigQuery中使用UDF时,是否可以在窗口之间保持共享状态?

问题描述

这是我的previous question的后续问题,内容涉及能够在BigQuery中模拟聚合函数(例如PGsql中的)。

一个问题中提出的解决方案确实适用于每个窗口上应用的函数独立于前一个窗口的情况-例如计算简单平均值等,但是在计算递归函数(例如指数移动平均值)时,公式为: EMA[i] = price[i]*k + EMA[i-1]×(1−k)

使用上一个问题中的相同示例,

CREATE OR REPLACE FUNCTION temp_db.ema_func(arr ARRAY<int64>,window_size int8)
RETURNS int64 LANGUAGE js AS """
    if(arr.length<=window_size){
        // calculate a simple moving average till end of first window
        var SMA = 0;
        for(var i = 0;i < arr.length; i++){
            SMA = SMA + arr[i]
        }
        return SMA/arr.length
    }else{
        // start calculation of EMA where EMA[i-1] is the SMA we calculated for the first window
        // note: hard-coded constant (k) for the sake of simplicity
        // the problem: where do I get EMA[i-1] or prev_EMA from?
        // in this example,we only need the most recent value,but in general case,we would 
        // potentially have to do other calculations with the new value 
        return curr[curr.length-1]*(0.05) + prev_ema*(1−0.05)
    }
""";

select s_id,temp_db.ema_func(ARRAY_AGG(s_price) over (partition by s_id order by s_date rows 40 preceding),40) as temp_col
from temp_db.s_table;

在PGsql中将状态变量存储为自定义类型非常容易,并且是聚合函数参数的一部分。可以使用BigQuery模仿相同的功能吗?

解决方法

我认为BigQuery无法通用完成此操作,而是希望了解具体情况并查看是否有合理的解决方法。同时,BQ尚不希望再次提供递归和聚合UDF,因此您可能要提交各自的feature request(s)

同期结帐BQ scripting,但我认为您的情况不适合

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...