DEV Community

loading...

A practical introduction to Redis for the Node.js developers

Farzad Aziminia
Software Architect and animal lover. Technology enthusiast. Full-stack and stack agnostic
・5 min read

Redis

Redis is a Key-Value “In-memory Database”. Ok, what is the “In-memory Database”? What is a Key-Value Store?

key-value database

According to Wikipedia “A key-value database, or key-value store, is a data storage paradigm designed for storing, retrieving, and managing associative arrays, and a data structure more commonly known today as a dictionary or hash table.”
In a simpler explanation: You create a key, for example, “username” and assign a value to it, for example, “john”. From there, you can get, update or delete the value associated with your key. Let’s see that in action. First, We need to install Redis. I’m using docker. If that is not your preferred way, visit https://redis.io/download.

docker run --name test-redis -p 6379:6379 -d redis 

Then verify your installation by running docker ps

Now let’s get into coding. We need to install the Redis client library.

Now create your package.json file and insert following code:

{
 "name": "redisexample",
 "version": "1.0.0",
 "author": "Farzad Aziminia",
 "license": "ISC",
 "dependencies": {
   "redis": "^3.0.2"
 }
}

Now run

npm install

Ok, It’s time to get our hands dirty. Create a file called app.js and insert the code below to it. Now run the node app.js

const redis = require('redis');
const client = redis.createClient();

client.set('foo', 'bar', redis.print);
client.get(foo, redis.print);

You create a “key” called “foo” and you set the value of “bar” to it. Next, you got the value of “foo” back. This is the “Key-Value” store in a nutshell.
Because I’m using Redis’s default authentication (Which is not recommended for production), I don’t need to pass username, password to createClient method. Redis.print basically prints the result of callback from the set and the get method.
Now we know what is Key-Value datastore, What is In-Memory Database?

In-Memory Database

In-Memory Database (IMDB) is a data management paradigm that utilizes computer memory to attain minimal response time by eliminating disk operations. We store our data in memory because usually memory access is way faster than disk access. You may ask: What are the downsides? Why do we still need to use DMS which relies on disk? Although solutions like Redis offer persistence, one drawback of using an in-memory database is: You will lose all of your data when the machine loses power or restarts, Another drawback can be related to cost, Computer memory tends to be more expensive than disk. These days you can purchase terabytes of disk space for a few hundred dollars.

Data structures

Unlike common key-value stores, Redis offers more than just string values. I'm not gonna cover all of them but you can learn more on https://redis.io/topics/data-types-intro.

Binary-safe strings

This is the most common data structure among key-value stores. Like we described above, simply pick a key and assign a value to it. Since both the key and the value are string in this structure, we can say it is a string to string binding.
The common operations are, Set, Get, Delete. Let’s update our example.

const redis = require('redis');
const client = redis.createClient();
client.set('user', 'admin', redis.print);
client.get('user', redis.print);
// Update our user
client.set('user', 'bob', redis.print);
client.get('user', redis.print);
client.del('user', redis.print);
client.get('user', redis.print);

One of the nice features that Redis is providing us is the expiration date or time to live. You can create a key and assign a “time to live” to it.

const redis = require('redis');
const client = redis.createClient();
client.set('session', '123', redis.print);
client.expire('session', 3, redis.print);
client.get('session', redis.print);

setTimeout(()=>{client.get('session', redis.print);}, 3000);

As you can see, after you create a key you can the expire method to set expiration in seconds. If you get an expired key you’ll get null.

Hashes

Hashes are a set of key values associated with a key. There is no limit to the number of fields you can add to a key. This is very similar to JSON. Common methods associated with the hashes are, hmset, hget, and hgetall. Let’s use them in an example:

const redis = require('redis');
const client = redis.createClient();

client.hmset('user01', 'name', 'bob', 'interest', 'football', redis.print);
client.hmset('user02', 'name', 'edward', 'interest', 'basketbal', redis.print);
client.hget('user01', 'name', redis.print);
client.hget('user02', 'name', redis.print);
client.hgetall('user01', (err, user)=>console.log(user));

Hashes are very memory efficient and a very good way of storing objects temporarily for frequent access.

Sets

Sets are an unordered collection of strings. You can call it “an unordered array of strings”. One thing that you need to keep in your mind is, Sets are non-repeating. Meaning you cannot repeat a given string in the set. Here is how you can create a set and get the members of a set:

const redis = require('redis');
const client = redis.createClient();

client.sadd('daysOfWeek', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday');
client.smembers('daysOfWeek', (err, value)=>console.log(value))

As you can see, You can add a member to a given list with the “sadd” method and get the list of all members of a list by “smembers” method also The returned result is not in the same order that you have saved. This is totally normal behavior of Redis set. That bring us to Ordered Sets

Ordered Sets
Ordered Sets are very similar to Sets. They are non-repeating set of string but the difference is, every member is associated with a “Score”. Redis uses that score in order to sort the array.

const redis = require('redis');
const client = redis.createClient();

client.zadd('daysOfWeek', 1, 'Sunday', 2, 'Monday', 3, 'Tuesday', 4, 'Wednesday', 5, 'Thursday');
client.zrange('daysOfWeek', 0, -1, (err, value) => console.log(value))

Zadd is the method you need to use in order to create an ordered set and insert members to it. You start with naming your set and add score followed by the value associated with the score. In our example, 1 is associated with Sunday, 2 with Monday, etc….
Then we used zrange to query our set. With zrange you can specify the start point and the endpoint of your range then Redis will return the result. It’s important to remember that the result is already sorted by the score that you provided. Zrange accepts both positive and negative numbers where 0 is the first element and 1 is the second element. Also, -1 is the last element and -2 is the one before the last element. In our case, we stated 0 which is the first element as our start point and -1 which is the last element of the set as our endpoint.

Conclusion
We talked about the concept of the In-memory Database in general and why we need it. We used Docker to run the Redis server and used redis-client library to connect to it. Then we talked about some of the important data types available and we did a couple of coding exercises.

Next, I’ll talk about Javascript Objects and variable instantiation.

Discussion (0)