@redis/time-series
This package provides support for the RedisTimeSeries module, which adds a time series data structure to Redis.
Should be used with redis
/@redis/client
.
:warning: To use these extra commands, your Redis server must have the RedisTimeSeries module installed.
Usage
For a complete example, see time-series.js
in the Node Redis examples folder.
Creating Time Series data structure in Redis
The TS.CREATE
command creates a new time series.
Here, we'll create a new time series "temperature
":
import { createClient } from 'redis';
import { TimeSeriesDuplicatePolicies, TimeSeriesEncoding, TimeSeriesAggregationType } from '@redis/time-series';
...
const created = await client.ts.create('temperature', {
RETENTION: 86400000,
ENCODING: TimeSeriesEncoding.UNCOMPRESSED,
DUPLICATE_POLICY: TimeSeriesDuplicatePolicies.BLOCK,
});
if (created === 'OK') {
console.log('Created timeseries.');
} else {
console.log('Error creating timeseries :(');
process.exit(1);
}
Adding new value to a Time Series data structure in Redis
With RedisTimeSeries, we can add a single value to time series data structure using the TS.ADD
command and if we would like to add multiple values we can use the TS.MADD
command.
let value = Math.floor(Math.random() * 1000) + 1;
let currentTimestamp = 1640995200000;
let num = 0;
while (num < 10000) {
await client.ts.add('temperature', currentTimestamp, value);
console.log(`Added timestamp ${currentTimestamp}, value ${value}.`);
num += 1;
value = Math.floor(Math.random() * 1000) + 1;
currentTimestamp += 1000;
}
const response = await client.ts.mAdd([{
key: 'temperature',
timestamp: currentTimestamp + 60000,
value: Math.floor(Math.random() * 1000) + 1
}, {
key: 'temperature',
timestamp: currentTimestamp + 120000,
value: Math.floor(Math.random() * 1000) + 1
}]);
Retrieving Time Series data from Redis
With RedisTimeSeries, we can retrieve the time series data using the TS.RANGE
command by passing the criteria as follows:
const fromTimestamp = 1640995200000;
const toTimestamp = 1640995260000;
const rangeResponse = await client.ts.range('temperature', fromTimestamp, toTimestamp, {
AGGREGATION: {
type: TimeSeriesAggregationType.AVERAGE,
timeBucket: 10000
}
});
console.log('RANGE RESPONSE:');
Altering Time Series data Stored in Redis
RedisTimeSeries includes commands that can update values in a time series data structure.
Using the TS.ALTER
command, we can update time series retention like this:
const alterResponse = await client.ts.alter('temperature', {
RETENTION: 0
});
Retrieving Information about the timeseries Stored in Redis
RedisTimeSeries also includes commands that can help to view the information on the state of a time series.
Using the TS.INFO
command, we can view timeseries information like this:
const tsInfo = await client.ts.info('temperature');