Skip to main content
You do not need one materialized view and one target table per bucket size, or a chain of cascading views. A single materialized view can multiply every inserted row with ARRAY JOIN, once per bucket size, and write all the buckets into one AggregatingMergeTree table whose sorting key starts with the bucket size.

Create the tables and the view

How it works:
  • ARRAY JOIN over two arrays of the same length walks them in parallel. Every source row becomes three rows, one per resolution, each with the start of its bucket.
  • GROUP BY resolution, bucket_start then aggregates each bucket of each resolution.
  • avgState stores an intermediate state instead of a final average, so that the buckets written by different inserts can be merged correctly. A count can be summed, so SimpleAggregateFunction(sum, UInt64) is enough for it.
  • ts has an explicit time zone, because the bucket boundaries computed by toStartOfDay and toStartOfHour depend on the time zone of the column.

Insert data and read one resolution

Insert two days of data, one request every ten seconds:
Read a resolution by filtering on it and finishing the aggregation with -Merge and sum. The filter on resolution and bucket_start uses the primary key of the target table:
The same aggregation over the source table returns the same four rows:

Get the latest bucket of every resolution

LIMIT 1 BY keeps the first row of each resolution, which is the most recent bucket of the day because of the descending order:

Costs and limits

  • The view aggregates every inserted row once per resolution, three times in this example.
  • Each inserted block adds one row per resolution and bucket it touches to the target table, and AggregatingMergeTree combines the rows of the same bucket in the background. Until then a bucket can have several rows, which is why the queries above always use GROUP BY with sum and avgMerge.
  • All resolutions share one table, one sorting key and one set of columns. If the bucket sizes need different ones, use cascading materialized views with one target table per bucket size instead.

Keep fine buckets for a shorter time

A single table can still expire each resolution separately, with a table TTL that has a condition per resolution:
MODIFY TTL changes the rule; existing parts are removed during later TTL merges. To apply the new rule to existing data immediately, materialize the TTL:
The example data is older than both limits, so after the TTL is materialized it keeps only the daily buckets.