DEV Community

Cover image for Redis Quick Tutorial!
Aria Azadi Pour
Aria Azadi Pour

Posted on

Redis Quick Tutorial!

In this article, you will learn about Redis and what it does, and how you can use it.

Install Redis

First, you need to install Redis. It is important to practice while learning. If you haven't already Installed Redis you can check out Redis's official download page or you can check out my article on How to install Redis on your OS of choice?. My preferred way of installing/using Redis is via Docker.

Redis, Itself

Redis is a very popular database. It is usually used for caching data and one of its main features is being an in-memory database which makes it very fast and very good for caching which is its main purpose.

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. Redis provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

from redis.io

Redis is a database in the family of key-value databases. That means you can store a value with a key and later on use that key to get the value again.

Redis Commands

Redis has multiple commands that you can use to work with the database. The commands have an overall structure, look at the example below:

> SET user:name "Aria"
Enter fullscreen mode Exit fullscreen mode

In the example at top, we are saving the value "Aria" with the key of "user:name". We will the SET command later but for now, let's focus on the structure of the command that we just called. Look at the structure below:

> ACTION (...arguments)
Enter fullscreen mode Exit fullscreen mode

In Redis, the structure is like what we have shown you at the top. ACTION is the command that we want to call, for example in our first example the SET command that we called is the action that we are asking Redis to take, and then the rest of the detail given to the command are the arguments that Redis uses to do the action that we have asked the database.

So with this knowledge in mind, let's continue our journey.

Basic Redis Commands

In this section, we are going to talk about the basic Redis commands, how we can save a key-value pair, and how to get and delete that value on the database.

Saving key-value pairs

One of the important things that we need to do is to save data on our database. For such action, we can use the SET command. Look at the syntax below:

> SET KEY VALUE
Enter fullscreen mode Exit fullscreen mode

Using this syntax we can save data in our databases. We need to replace the KEY with the chosen key and replace the VALUE with the value that we want to save on the database. Look at the example below:

> SET user:age 17
Enter fullscreen mode Exit fullscreen mode

So let's explain the example at the top. We are saving the value 17 with the key of user:age. Very basic, but very useful and important.

Getting value

After storing the value that we want in the database we need a way to receive the stored data. For this, we can use the GET command. Look at the syntax below:

> GET KEY
Enter fullscreen mode Exit fullscreen mode

Using this syntax we can receive the data stored in the database. We need to replace the KEY with the key that we used when we were saving the value in the database. Look at the example below:

> GET user:age
Enter fullscreen mode Exit fullscreen mode

If you did exactly as I did in the example of saving key-value pairs, you will receive the line bellow in the return of this command:

"17"
Enter fullscreen mode Exit fullscreen mode

See, quite easy to start. Using these commands we can save and receive the values that we need and it will be extremely fast to use this database to work with our data.

Deleting value

Now that we can store and receive the value that we have saved, it's time to take it forward and delete some of the values that we have said. For deleting stored values we use the syntax below:

> DEL KEY
Enter fullscreen mode Exit fullscreen mode

With this syntax, we will be able to delete the unwanted values saved on our database. Look at the example below:

> DEL user:age
Enter fullscreen mode Exit fullscreen mode

If you did exactly as I did in the examples before you will see the result of an (integer) 1, something like below:

(integer) 1
Enter fullscreen mode Exit fullscreen mode

If you try this command again you will receive an (integer) 0, meaning that the key that you have given to the command doesn't exist. The result will be something like below:

(integer) 0
Enter fullscreen mode Exit fullscreen mode

Getting non-existing value

When you delete a value or never create one with the key that you what to receive value with, you will get a nil value in return for your GET command. Look at the example below:

> GET user:age
Enter fullscreen mode Exit fullscreen mode

If you continued every step that I took, you will not have anything stored with the key of user:age and you will receive nil in the result. It will be something like below:

(nil)
Enter fullscreen mode Exit fullscreen mode

Check value existence

If you want to check if a key holds a value in the database you can use the EXISTS. Look at the syntax below:

> EXISTS user:age
Enter fullscreen mode Exit fullscreen mode

This will return an integer number, 1 or 0, 1 meaning yes, and 0 meaning no.

Let's store a new value in our database:

> SET user:occupation "developer"
Enter fullscreen mode Exit fullscreen mode

Now, let's check if it exists on the database or not:

> EXISTS user:occupation
Enter fullscreen mode Exit fullscreen mode

This will return an (integer) 1 in a result like below:

(integer) 1
Enter fullscreen mode Exit fullscreen mode

Now let's check if the record that we have deleted on the database, exists or not:

> Exists user:age
Enter fullscreen mode Exit fullscreen mode

This will return an (integer) 0, which means the record doesn't exist on the database. See the result below:

(integer) 0
Enter fullscreen mode Exit fullscreen mode

Now we know the basics of a Redis database and already we can do a lot with our knowledge but let's take it forward in the next sections.

Working With Numbers

In this section, we are going to cover a couple of commands to work with numbers in Redis. It's important to keep in mind that Redis doesn't save numbers and integers or floating points in the database and instead saves them as string, but if you use these commands on the string that are numbers it will work perfectly without any problems.

For this section, let's create a record to save the number of user's devices:

> SET user:devices 2
Enter fullscreen mode Exit fullscreen mode

Increasing and Decreasing numbers by 1

Redis has two commands that help us increase or decrease numbers by one, the INCR command is used to increase a number by one and the DECR command is used to decrease a number by one. Look at the syntax for increasing a number:

> INCR KEY
Enter fullscreen mode Exit fullscreen mode

And look at the syntax for decreasing a number:

> DECR KEY
Enter fullscreen mode Exit fullscreen mode

As you can see it is pretty clear and easy to work with these commands. When you call these commands it will return the new integer value. Look at the example below:

> INCR user:devices
Enter fullscreen mode Exit fullscreen mode

This will increase the value stored at user:devices by one and return the new value which in our case is (integer) 3. It will return the line below:

(integer) 3
Enter fullscreen mode Exit fullscreen mode

Now let's see an example of decreasing the number by one. Look at the example below:

> DECR user:devices
Enter fullscreen mode Exit fullscreen mode

This will also return the new value just like the increasing command. It will return the line below:

(integer) 2
Enter fullscreen mode Exit fullscreen mode

Increasing and Decreasing number by value of choice

Other than increasing and decreasing numbers by one we also can increase and decrease it with any value that we choose. There are two commands to do these actions, INCRBY and DECRBY. Look at the syntax for INCRBY:

> INCRBY KEY INCREMENT
Enter fullscreen mode Exit fullscreen mode

And look at the syntax below for DECRBY:

> DECRBY KEY DECREMENT
Enter fullscreen mode Exit fullscreen mode

In these syntaxes, the KEY is the key that we used to store the value like always and the INCREMENT and the DECREMENT should be replaced by the values that we want to use. Loot at the example below:

> INCRBY user:devices 2
Enter fullscreen mode Exit fullscreen mode

In this example, we are increasing the value stored by 2 and as the commands that we talked about before this command also return the new stored value, like below:

(integer) 4
Enter fullscreen mode Exit fullscreen mode

And the same goes for the example below:

> DECRBY user:devices 2
Enter fullscreen mode Exit fullscreen mode

In this example we are decreasing the value stored by 2 and same as before it will return the new value like below:

(integer) 2
Enter fullscreen mode Exit fullscreen mode

Errors in working with numbers

There can be some errors accrued while working with numbers that are important to keep in mind. In this part we are going to talk about some of the most problems accrued in this area and then talk about how numbers work more in detail.

Non-integer values

There can be many times which you accidentally or unknowingly use these commands on non-integer values. It is important to note that you can only use these commands on integers and you can't use them even on floating points.

Let's see this in practice. Now I'm going to store a new record in the database for the user's amount of money in the wallet:

> SET user:wallet 7.89
Enter fullscreen mode Exit fullscreen mode

Now let's try to increase it using the INCR command:

> INCR user:wallet
Enter fullscreen mode Exit fullscreen mode

If you try to take this action you will face the error below:

(error) ERR value is not an integer or out of range
Enter fullscreen mode Exit fullscreen mode

This error means that these actions can not be taken on the value stored with the provided key.

Out of range integers

As you see in the error accrued on incrementing non-integers, it said the value is either not an integer or out of range. Redis numbers work on a 64 bit signed integer system, so when you want to work with a number out of this system Redis will return an error.

Let's see this in action. First, we are going to store a new value in the database for the user's ID that exceeds the limit of a 64 bit signed system:

> SET user:id "12345678912345678901"
Enter fullscreen mode Exit fullscreen mode

The value that we have saved is clearly out of the 64 bit signed number system. Now let's try to increase the number using the INCR command:

> INCR user:id
Enter fullscreen mode Exit fullscreen mode

Using this command on this record in the database will return the familiar error that we saw in the past like below:

(error) ERR value is not an integer or out of range
Enter fullscreen mode Exit fullscreen mode

This time this error accrued because the number was too big for Redis to process and It is important to keep this note in mind and don't use increment and decrement commands for potentially big numbers.

Expiration

As I said Redis is used a lot for caching And if you know a little bit about caching you are aware that the data that has been cached is not there to stay forever and at some point, we want to get rid of it and set a new value or recalculate it or many other actions. We can easily automate such actions by setting an expiration date and time for the record that we want to save and that can be helpful for many developers and make their work easier with implementing many functionalities that if Redis didn't have it, it would take such a long time to implement a high-quality system like this.

Setting an expiration date

There are two ways to set an expiration date. One, setting it while storing data at Redis database, and two, setting expiration date after the record is stored in the database.

Setting expiration date while storing the record

First, let's talk about the first way. This isn't much different from how we stored the records before we just need to pass two more arguments to the SET command. Look at the syntax below:

> SET KEY VALUE EX SECONDS
Enter fullscreen mode Exit fullscreen mode

In the syntax shown at the top, the KEY and the VALUE is like before and we just need to add an EX at the end of our command and then put the expiration time in seconds in place SECONDS. Look at the example below:

> SET user:age 17 EX 2592000
Enter fullscreen mode Exit fullscreen mode

In this example, we are storing 17 with the key of user:age and setting the expiration time in 2592000 seconds from now which is the equivalent of 30 days from now. So after 39 days, this record will no longer exist on the database.

Note: Keep in mind you can use PX instead of EX in order to use milliseconds instead of seconds.

Setting expiration date after storing the record

After we stored the data there is still a way to put the expiration date for the record. We can use the EXPIRE command to take such action. Look at the syntax below:

> EXPIRE KEY SECONDS
Enter fullscreen mode Exit fullscreen mode

In this syntax, we need to replace the KEY with the key that we used to store our data, and then we can replace the SECONDS with the number of seconds that we want Redis to wait before removing the record from the database. Look at the example below:

> EXPIRE user:age 2592000
Enter fullscreen mode Exit fullscreen mode

If you did what we did before and stored a value with the user:age and expiration date of 2592000 seconds, This will just set the expiration date again. That means 30 days from when you called the command.

Checking remaining of expiration date

If you need to check how much time is left for the record to expire, you can use the TTL command. This command will return the number of seconds left before the record expiration. Look at the syntax below:

> TTL KEY
Enter fullscreen mode Exit fullscreen mode

In this syntax, we just need to use the key that we use to store the record and then we can get the remaining Seconds left to expire. Look at the example below:

> TTL user:age
Enter fullscreen mode Exit fullscreen mode

In this example, Redis will return the time left to expire for the record with the key of user:age. The return line will be something like below:

(integer) 2591685
Enter fullscreen mode Exit fullscreen mode

Note that depending on when you called the first command and when you called this command, you will receive different results.

One of the questions that you might have now is what happens when we call the TTL command on a record that doesn't have an expiration date. Well, the answer is simple it will just return an (integer) -1 to indicate that this record doesn't have an expiration date. The return line will be something like below:

(integer) -1
Enter fullscreen mode Exit fullscreen mode

Removing expiration date

One of the other actions that you might what to take after putting an expiration date on a record, is to remove the expiration date if necessary. Well, we can do that using the Persist command. This command will help us remove the expiration date. Look at the syntax below:

> PERSIST KEY
Enter fullscreen mode Exit fullscreen mode

All you have to do to remove a record's expiration date is to use its key instead of KEY and you will have its expiration date removed. Look at the example below:

> PERSIST user:age
Enter fullscreen mode Exit fullscreen mode

This example will remove the expiration date of the record with the key of user:age and if we call the TTL command on this record, we will receive an (integer) -1.

Note: Keep in mind you can use PEXPIRE and PTTL commands instead of EXPIRE and TTL commands in order to use milliseconds instead of seconds.

Lists

In this section, we are going to talk about one of the more advanced data structures in Redis. Everything that we have talked about until this point was just string. Even the numbers that we talked about at the end of the day are saved as strings inside the database. So we are going to learn how we can use Lists inside Redis with a couple of simple commands.

Storing lists and adding item to lists

Storing a list in a Redis database is somewhat different from what you might expect. To start it doesn't happen with the SET command and you need to use another set of commands to work with lists.

To add an Item to the list or create a list, We use RPUSH and LPUSH commands. The RPUSH command adds one or more items from right to our list and the LPUSH command adds one or more items from left to our list. Look at the syntaxes below:

> LPUSH KEY VALUE (...VALUE)
> RPUSH KEY VALUE (...VALUE)
Enter fullscreen mode Exit fullscreen mode

As always KEY is the key that we use the save the record on the database and VALUE is the value that we want to add to the list. It is important to keep in mind you can add more than one value with one command and that is why we have the (...VALUE) to represent unnecessary more than one value. Look at the example below:

> LPUSH user:languages "English" "Persian" "Kurdish"
Enter fullscreen mode Exit fullscreen mode

In this example, we are creating a new record with the type of list and key of user:languages and adding English, Persian, and Kurdish to the list. If we want to add more we can just use this command again and add more items to the list. Look at the example below:

> RPUSH user:languages "Arabic"
Enter fullscreen mode Exit fullscreen mode

In the example above, using the RPUSH command we are pushing a new item to the right of the list with the key of user:languages.

These commands will return an integer in the result that indicates the length of our list. For example, this was the return line of the last command:

(integer) 4
Enter fullscreen mode Exit fullscreen mode

Another important point to make is that when we use RPUSH and LPUSH commands with multiple items, it won't take the items we gave to them and put them directly inside the right or left of the list. It will go one by one over our items and take the actions on them. This means when we called LPUSH user:languages "English" "Persian" "Kurdish", first "English" was pushed to the left side then "Persian" was pushed to the left, and finally "Kurdish" was pushed to the left of our list, which makes "Kurdish" the first item of our list from left and "English" the last item of our list from left.

Getting stored lists

While working with a list we are going to deal with list indexes. The index of each list starts from left with the number of 0 and as we move on the items, the number of the index increases each item that we pass. In Redis, if we want to get items index from right we use negative integers. That means the first index from the right is -1 because we don't have negative or positive 0 and it's just 0. If you are confused, the image below might help you a lot.

List Index System

So with this indexing system in mind let's explain the next command that helps us get items inside a list. To get items inside a list, we can use LRANGE. The LRANGE command helps us get items that are between two indexes. Look at the syntax of this command:

> LRANGE KEY START STOP
Enter fullscreen mode Exit fullscreen mode

At this point I expect you to know what the KEY argument is. So with that in mind let's explain the two remaining arguments. First, let's talk about the START argument, this argument determines the index of the first item in the list that Redis should return for us. Now let's talk about the STOP argument, this argument determines the index of the last item in the list that Redis should return for us, and this command together will provide Redis with a range of items that should return in response for us. Let's take a look at this example:

> LRANGE user:languages 0 -1
Enter fullscreen mode Exit fullscreen mode

This example will return every item in the list for us because 0 is the first index in the list and -1 is the last index in the list. The results should be something like below:

1) "Kurdish"
2) "Persian"
3) "English"
4) "Arabic"
Enter fullscreen mode Exit fullscreen mode

Removing items from lists

Now that we can store and receive items from our list, it's time to find out how we can remove items from our list. There are two commands to remove the items from our list, RPOP and LPOP. These two commands will help us pop(remove) an item from the left or right of the list. Look at the syntaxes below:

> RPOP KEY
> LPOP KEY
Enter fullscreen mode Exit fullscreen mode

The RPOP command will remove an item from the right of our list and the LPOP command will remove an item from the left of our list. All we need to do is provide Redis with the list's key. Look at the example below:

> RPOP user:languages
Enter fullscreen mode Exit fullscreen mode

This will remove an item from the end of the list and return the removed item. The return line for the example that we just showed, would be something like below:

"Arabic"
Enter fullscreen mode Exit fullscreen mode

List length

One last command for working with lists that we will cover in this article is the LLEN command. This command will help us get the length of our list. Look at the syntax below:

> LLEN KEY
Enter fullscreen mode Exit fullscreen mode

Using this simple command we will get the length of the list with the provided key. Look at the example below:

> LLEN user:languages
Enter fullscreen mode Exit fullscreen mode

This command will return an integer number showing the length of our list. The result will be something like below:

(integer) 3
Enter fullscreen mode Exit fullscreen mode

Sets

In this section, we are going to talk about another advanced data structure in Redis world, Set. Set is a collection just like list. Sets aren't ordered, which means there is no index when working with sets. Another important feature is the uniqueness of each item and there can't be multiple equal items in one set, unlike lists.

Storing sets and add members to sets

Just like lists, there are no initial declarations for sets, and adding the first member to the set will automatically create the set. In order to add a member to a set, we use the SADD command. Look at the syntax below:

> SADD KEY MEMBER (...MEMBER)
Enter fullscreen mode Exit fullscreen mode

As we have seen in working with lists, this is a very familiar syntax. We can add one or multiple members to a set using this syntax. Look at the example below:

> SADD user:skills "redis"
Enter fullscreen mode Exit fullscreen mode

In this example, we are creating a new set with one member. This command will return the new length of the set. For example in this case the return line will look like below:

(integer) 1
Enter fullscreen mode Exit fullscreen mode

Removing members from sets

Now we can move on to how we can remove members from a set. This action can be taken using the SREM command. Look at the syntax below:

> SREM KEY MEMBER (...MEMBER)
Enter fullscreen mode Exit fullscreen mode

Using this syntax you can remove one or multiple members of a set associated with the provided key. Look at the example below:

> SREM user:skills "redis"
Enter fullscreen mode Exit fullscreen mode

In this example, we are removing "redis" from the set with the key of user:skills. The result of this action will be either an integer 1 or an integer 0. 1 meaning the "redis" was a member of the set and 0 meaning that it wasn't a member of the set.

Checking if a value is member of a set

We can also check if a value is a member of a set using the SISMEMBER command. Look at the syntax below:

> SISMEMBER KEY MEMBER
Enter fullscreen mode Exit fullscreen mode

Using this syntax we can check for the existence of one member in the set. Loot at the example below:

> SISMEMBER user:skills "redis"
Enter fullscreen mode Exit fullscreen mode

This action will check if "redis" is a member of user:skills. This will return an integer number, 1 meaning value is member of the set and 0 meaning value is not a member of the set.

Getting members of a set

Getting members of a set is the last part that we are going to cover related to sets. To get members, we use the SMEMBERS command. Look at the syntax below:

> SMEMBERS KEY
Enter fullscreen mode Exit fullscreen mode

As you see all we need to provide Redis is the key associated with our record and then we can get all the members of a set. To test this, first let's add some members to our set using the command below:

> SADD user:skills "redis" "express" "react"
Enter fullscreen mode Exit fullscreen mode

Now let's test our new command:

> SMEMBERS user:skills
Enter fullscreen mode Exit fullscreen mode

As we said before this will return all the members of this set. The return line will look something like the below:

1) "react"
2) "redis"
3) "express"
Enter fullscreen mode Exit fullscreen mode

Sorted sets

This is one of the newest Redis data structures. We are going to talk a little bit about it to just introduce you to the data structure because this is a quick tutorial and it has already become a very long article. A sorted set is just like the normal set with only one difference, each member is associated with a score when you are creating it and that allows Redis to sort it. We aren't going to cover any commands but you can checkout the documents on the Redis's official website.

Hashes

The last data structure that we are going to cover is hashes. Hashes are maps with string keys and string values and they are the perfect data type to represent objects.

Storing fields

Just like the lists and sets, hashes also doesn't have any form of declaration and by storing the first field you have already created the hash. To create a field, we use the HSET command. Look at the syntax below:

> HSET KEY FIELD VALUE
Enter fullscreen mode Exit fullscreen mode

Using this syntax we can create a field on a hash. Now let's try to recreate our user's model using hashes. Look at the example below:

> HSET user name "Aria"
Enter fullscreen mode Exit fullscreen mode

In this example, we are creating a field named name on the hash with the key of user.

Receive data from hashes

There are two ways to receive data from hashes. One, getting data of all of the fields at once, and two, getting data of each field alone.

Let's talk about the first way. In order to get every field of a hash, we can use the HGETALL command. Look at the syntax below:

> HGETALL KEY
Enter fullscreen mode Exit fullscreen mode

Using this syntax we can get all of the hash's fields and values. It will represent the data in a special way. Let's see this in action:

> HGETALL user
Enter fullscreen mode Exit fullscreen mode

In this example, we are getting every field and value on the hash with the key of user. Redis returns the data in a list. The odd indexes are fields and the even indexes are values of that fields. Take a look at the return line of this command:

1) "name"
2) "Aria"
Enter fullscreen mode Exit fullscreen mode

In here "name" is the field and "Aria" is the value. If we had more fields it would continue with the same pattern.

Deleting fields

We are also able to delete each field instead of deleting the hash altogether. To delete a field we use the HDEL command. Look at the syntax below:

> HDEL KEY FIELD (...FIELD)
Enter fullscreen mode Exit fullscreen mode

Here we need to provide the key of the hash and the name of the fields that we want to remove. Look at the example below:

> HDEL user name
Enter fullscreen mode Exit fullscreen mode

In here we are removing the field name from the hash with the key of user. This action as always will return an integer number to indicate if the field or fields existed on the hash or not.

Final Words

There are many more commands to work with Redis especially with hashes and sorted sets and there is much more than you can explore and learn. This was just a short article to take you to a certain level to make you able to work better with Redis. Continue your journey with Redis. One of the best sources is Redis's official website that I highly recommend for you to check out and see its documents. Have a good journey.

Resources

Huge thanks to the Try Redis website that has helped a lot with the order of this tutorial.

Find Me

Discussion (0)