Aggregate Types
SimpleAggregateFunction stores pre-aggregated values that ClickHouse automatically merges when combining rows with the same primary key. Use with AggregatingMergeTree tables.
SimpleAggregateFunction
Define columns that automatically aggregate during merges:
import { SimpleAggregated, OlapTable, ClickHouseEngines, Key, DateTime } from "@514labs/moose-lib"; interface DailyStats { date: DateTime; userId: string; totalViews: number & SimpleAggregated<"sum", number>; maxScore: number & SimpleAggregated<"max", number>; minLatency: number & SimpleAggregated<"min", number>; lastSeen: DateTime & SimpleAggregated<"anyLast", DateTime>;} const statsTable = new OlapTable<DailyStats>("daily_stats", { engine: ClickHouseEngines.AggregatingMergeTree, orderByFields: ["date", "userId"],});Supported Aggregate Functions
| Function | Description | Typical Use |
|---|---|---|
sum | Sum of values | Totals, counts |
max | Maximum value | Peak metrics |
min | Minimum value | Minimum thresholds |
any | Any single value | Non-deterministic pick |
anyLast | Last inserted value | Latest timestamp, status |
argMax | Value at max of another column | Value when metric was highest |
argMin | Value at min of another column | Value when metric was lowest |
How It Works
- Insert: Data is written with initial aggregate values
- Background Merge: ClickHouse periodically merges rows with the same ORDER BY key
- Automatic Aggregation:
SimpleAggregateFunctioncolumns are combined using their specified function
// Two rows with same (date, userId):{ date: "2025-01-01", userId: "u1", totalViews: 10 }{ date: "2025-01-01", userId: "u1", totalViews: 15 } // After merge:{ date: "2025-01-01", userId: "u1", totalViews: 25 } // sumWhen to use SimpleAggregateFunction
Use when you need real-time aggregations on high-volume data. Instead of storing every event and aggregating at query time, pre-aggregate during ingestion for faster queries.
Requires AggregatingMergeTree
SimpleAggregateFunction only works with AggregatingMergeTree or ReplicatedAggregatingMergeTree table engines. The table's ORDER BY clause defines which rows get merged.
See Also
- ClickHouse SimpleAggregateFunction docs
- Table Engines for configuring
AggregatingMergeTree