Does timescaledb support window functions?

jbx*_*jbx 4 postgresql materialized-views window-functions timescaledb continuous-aggregates

I am trying to use the TimescaleDB extension to compute some continuous aggregates. I have this query which works fine:

SELECT distinct time_bucket('1 hour', entry_ts) as date_hour,
                type_id,
                entry_id,
                exit_id,
                count(*) OVER (partition by time_bucket('1 hour', entry_ts), entry_id, exit_id, type_id) AS total,
                ((count(*) over (partition by time_bucket('1 hour', entry_ts), entry_id, exit_id, type_id)) * 100)::numeric /
                (count(*) over (partition by time_bucket('1 hour', entry_ts), entry_id)) percentage_of_entry
FROM transits
Run Code Online (Sandbox Code Playgroud)

When I try to put this inside a continuous aggregate materialized view, I get an error:

CREATE MATERIALIZED VIEW transits_hourly
            WITH (timescaledb.continuous) AS
SELECT distinct time_bucket('1 hour', entry_ts) as date_hour,
                type_id,
                entry_id,
                exit_id,
                count(*) OVER (partition by time_bucket('1 hour', entry_ts), entry_id, exit_id, type_id) AS total,
                ((count(*) over (partition by time_bucket('1 hour', entry_ts), entry_id, exit_id, type_id)) * 100)::numeric /
                (count(*) over (partition by time_bucket('1 hour', entry_ts), entry_id)) percentage_of_entry
FROM transits
WITH NO DATA
Run Code Online (Sandbox Code Playgroud)

The error I get is:

ERROR:  invalid continuous aggregate view
SQL state: 0A000
Run Code Online (Sandbox Code Playgroud)

Does TimescaleDB allow Continuous Aggregates over Partition By time windows?

I am using TimescaleDB 2.1 on PostgreSQL 12.5.

k_r*_*rus 5

TimescaleDB 是一个 PostgreSQL 扩展,允许使用 PostgreSQL 的大部分功能。hypertables 上的 SELECT 语句没有已知的限制。

然而,连续聚合支持有限的查询,因此它可以增量地维护物化而不是刷新整个物化,这将是昂贵的。基本上查询应该允许独立于其他组处理每个聚合组,因此DISTINCT不允许使用窗口函数。

创建连续聚合的文档包含一个注释小节,其中包含对 SELECT 语句的限制列表。特别是:

不允许使用 ORDER BY、DISTINCT 和 FILTER 子句的聚合。

窗口函数不能与连续聚合结合使用。

解决限制的可能方法:

  • 使用允许的 SELECT 语句创建一个连续聚合,然后在其上定义一个视图,它将计算最终结果。这可以减少最终视图要处理的数据量,但执行起来仍然很昂贵。
  • 创建物化视图并创建刷新它的自动化,例如,在自定义作业的帮助下。但是,刷新将重新计算整个物化。
  • 如果您对如何计算部分数据的查询有一个很好的想法,您可以将插入脚本写入另一个表,该脚本将专门用于存储物化。然后可以通过例如自定义作业自动实现物化。