One way to implement a time-series using Redis

mo2men_1

Mo'men Ahmed

Posted on May 23, 2021

One way to implement a time-series using Redis

What is Redis?

Redis stands for 'REmote DIctionary Server', so the name itself implies a dictionary (key-value pairs).

Why use Redis?

Redis is used as a database cache to save data in a fast way in the form of key-value pairs. Also, wide use for it is for sending messages between different systems through a shared Redis database.

What types of data can be stored in Redis?

Redis provides data structures such as strings, hashes, lists, sets, and sorted sets.

How to use Redis?

First, you need to install it from their website. Then you can choose to work in redis-cli or any language client, here we use python redis client. You can install redis for python by pip install redis. This python library has all redis-cli commands as functions, This is a cheatsheet for Redis commands.

A great VS Code extension for Redis

I use this extension in VS Code, it can view all the contents in Redis in a nice and easy way.

image

An Example on Redis string data type

First, we make a Redis instance by r = redis.Redis(redisServer, 6379)
then we set a value to a key and get it:

r.set('name', 'Ali')
r.get('name')
Enter fullscreen mode Exit fullscreen mode

so, now we have a key called 'name' and has a value called 'Ali'.

An Example on Redis hash data type

# r.hset('price', 'time', 'value')
r.hset('price', '12:20:00', '250.0')
r.hset('price', '12:20:15', '250.7')
r.hset('price', '12:20:30', '252.0')
Enter fullscreen mode Exit fullscreen mode

You can get the value of any time by:

r.hget('price', '12:20:15')
Enter fullscreen mode Exit fullscreen mode

so, it will return the value '250.7'.

You can also get all values and keys by:
image

Redis Time-series using Hash

The idea about making a time-series in Redis is to have a key for each column you have, and use a hash data type for each one, each hash has a field and a value in the format {field: value}. We put the timestamp as the field.

An example will be like this:
image

💖 💪 🙅 🚩
mo2men_1
Mo'men Ahmed

Posted on May 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related