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
ARRAY JOINover 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_startthen aggregates each bucket of each resolution.avgStatestores 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, soSimpleAggregateFunction(sum, UInt64)is enough for it.tshas an explicit time zone, because the bucket boundaries computed bytoStartOfDayandtoStartOfHourdepend on the time zone of the column.
Insert data and read one resolution
Insert two days of data, one request every ten seconds:-Merge and sum. The filter on resolution and bucket_start uses the primary key of the target table:
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
AggregatingMergeTreecombines the rows of the same bucket in the background. Until then a bucket can have several rows, which is why the queries above always useGROUP BYwithsumandavgMerge. - 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: