How to create a materialized view for existing table in Timescale?

Viewed 544

When I'm trying to create materialized view for existing table by query:

CREATE MATERIALIZED VIEW current_data_hourly
WITH (timescaledb.continuous) AS
SELECT id,
        time_bucket(INTERVAL  '1 hour', creation_time) AS creation_time,
       AVG(current_abs_1_avg),
       MAX(current_abs_1_max),
       MIN(current_abs_1_min)
FROM time_series.current_data
GROUP BY id, creation_time;

I'm getting:

ERROR:  continuous aggregate view must include a valid time bucket function
SQL state: XX000

Any suggestions what could be wrong?

1 Answers

In the view query above, the grouping is ambiguous between the input column name, which is creation_time in hypertable time_series.current_data, and the output column name, which is defined as time_bucket(INTERVAL '1 hour', creation_time) AS creation_time. According to GROUP BY description in SELECT documentation:

In case of ambiguity, a GROUP BY name will be interpreted as an input-column name rather than an output column name.

I.e., creation_time is not the one, which is alias for time_bucker expression. Thus the error.

One way to fix is to use the positions of the columns from the SELECT clause:

CREATE MATERIALIZED VIEW current_data_hourly
WITH (timescaledb.continuous) AS
SELECT id,
        time_bucket(INTERVAL  '1 hour', creation_time) AS creation_time,
       AVG(current_abs_1_avg),
       MAX(current_abs_1_max),
       MIN(current_abs_1_min)
FROM time_series.current_data
GROUP BY 1, 2;
Related