# TS.AGG

> Aggregate the samples of a time series into fixed-width time buckets.

URL: https://docs.hotkv.com/commands/ts-agg/

```
TS.AGG key from to bucket aggregation
```

- Group: Time series
- Complexity: O(log N + M), M being the samples in the range
- HotKV Cloud: Performance and Scale plans
- On-Premise: requires the time-series license feature

`TS.AGG` groups the samples of the time series `key` between `from` and `to`
into buckets `bucket` milliseconds wide, and returns one aggregated value per
bucket.

Buckets start at `from` and follow each other every `bucket` milliseconds;
with `from` given as `-`, they are aligned to the Unix epoch. Only buckets
that hold at least one sample are returned, each labeled with its start time.

## Arguments

| Argument | Meaning |
| --- | --- |
| `from` | Start, in Unix milliseconds, or `-` for the earliest. |
| `to` | End, in Unix milliseconds, or `+` for the latest. |
| `bucket` | Bucket width in milliseconds, at least 1. |
| `aggregation` | One of the functions below, all in lower case or all in upper case. |

| Aggregation | Value per bucket |
| --- | --- |
| `avg` | Mean of the values. |
| `min`, `max` | Lowest or highest value. |
| `sum` | Sum of the values. |
| `count` | Number of samples. |
| `first`, `last` | Value of the earliest or latest sample. |
| `range` | Highest minus lowest value. |
| `std.p` (or `stddev`) | Population standard deviation. |

## Return value

An array of buckets, each `[start-timestamp, value]`: the start as an integer
and the value as a bulk string with six decimals. The shape is the same in
RESP2 and RESP3. A series that does not exist, or has no samples in the
range, gives an empty array.

Error replies: `ERR invalid timestamp range`, `ERR invalid bucket size`,
`ERR unknown aggregation type`, and `NOLICENSE ...` without the
`time-series` license feature.

## Examples

```
127.0.0.1:6379> TS.CREATE cpu
OK
127.0.0.1:6379> TS.ADD cpu 1700000000000 20
(integer) 1700000000000
127.0.0.1:6379> TS.ADD cpu 1700000030000 22
(integer) 1700000030000
127.0.0.1:6379> TS.ADD cpu 1700000060000 24
(integer) 1700000060000
127.0.0.1:6379> TS.ADD cpu 1700000090000 30
(integer) 1700000090000
127.0.0.1:6379> TS.AGG cpu 1700000000000 1700000119999 60000 avg
1) 1) (integer) 1700000000000
   2) "21.000000"
2) 1) (integer) 1700000060000
   2) "27.000000"
127.0.0.1:6379> TS.AGG cpu 1700000000000 + 60000 max
1) 1) (integer) 1700000000000
   2) "22.000000"
2) 1) (integer) 1700000060000
   2) "30.000000"
```

## Compatibility

HotKV-only command. RedisTimeSeries offers aggregation through options of
its `TS.RANGE` command instead.

## See also

[TS.RANGE](https://docs.hotkv.com/commands/ts-range/index.md), [TS.DOWNSAMPLE](https://docs.hotkv.com/commands/ts-downsample/index.md), [TS.ADD](https://docs.hotkv.com/commands/ts-add/index.md)