Codementor Events

Delving further into Redis

Published Mar 26, 2018Last updated Sep 22, 2018

Ok i’ll admit i haven’t been using Redis for anything like its potential but recently i’ve been given the opportunity to look at redis as more than just an object store. A project that i’ve been working on required a light and fast DB for user data storage and with more reads being done than writes, no-sql was the way to go.

So, as previous posts i’ve done i have mainly used Redis to just put stuff (caching data) in so that i could get it out later. It turns out that i have been looking at Redis in the wrong way. There is no reason why you can not store a UserId in there which you can then link to something else.

There first question you may have is how to keep the ID’s unique without having to keep a counter in a separate variable. This is answer easy by having a key UniqueID and setting this to 0

set UniqueId 0 get UniqueId - returns 0

Here we are. A key with the value of 0. Where am i going with this? incr. Redis provides a mechanism to increment a value in a key.

incr UniqueId get UniqueId - returns 1

Of course this doesn’t have to be used like this and there are many other ways of making a key unqiue (UUID’s being one) but as Redis is running in memory, we should always be mindful of space. Numbers taking less space up than Strings.

Right so i’ve got a way of making a user key unqiue and i have some users that i would like to add. Here is where we have a design decision to make. Do we put everything in a hash or do we split up the data and have a way of sticking it all back together? For the sake of speed and not always needing all the data, we’ll split it up. For this i’ll add a key with the users login (as this should also be unique) making use of the UniqueId.

SET User:1 JoeBlogs HMSET User:1:Details firstname Joe surname Blogs

And if for example we are making a DB which users becoming members of chat rooms. We could then use a SET which we can then create a list of unique rooms that a user is connected with. The reason for using a SET here is because repeated strings can not be inserted into a SET.

sadd User:1:Rooms Maths Javascript Nodejs

To recap. In this example. We’ve created a key that we can use as a unique number by incrementing the value and the reason that we use number is that it is going to take up less space in memory than a string. We have used the incremented number to create a unquie key for user 1 and then added a hash (1 level object) for the user. Then finally we have created a set for the user with all the rooms that they are connected with.

Discover and read more posts from Dominic Scanlan
get started