Introduction to Redis Using Python

TK Kaushik Jegannathan 27 Jun, 2022 • 5 min read

This article was published as a part of the Data Science Blogathon.

Introduction

Redis is a popular in-memory key-value data store, which is a type of NoSQL database. Redis is chiefly used as a cache database, but its application does not end there. You can find many articles explaining how Redis can be the all-in-one database for all kinds of applications. In this article, we will understand how to connect and use Redis in python.

Installing Redis on Windows

Redis is not officially supported on Windows. However, you can install Redis by setting up Windows Subsystem for Linux 2 and configuring it. Alternatively, you can run Redis on a container using Docker, which I will be covering in this article. The first step is to install Docker on your Windows machine. You can download Docker Desktop from here. The installation process is fairly simple and direct. Now that we have Docker on our machine, enter the following command on a command prompt to fetch the Redis image from Docker Hub, which can be used to build and run a container.

docker pull redis

Once this is done, the third step is to start a container using the Redis image that we downloaded earlier.

Redis

Here, click on the ‘RUN’ button.

Redis

Please refer to the below picture for reference.

containers | Redis

Congrats, you have now successfully started the Redis server on your machine.

Installing Redis-py

To connect and use Redis in python, we will be using a python module called redis-py. It can be installed by running the following command in the command prompt.

pip install redis

Now that we have everything ready, let’s get our hands dirty and dive into the programming part.

Using Redis-py

Before performing any CRUD operations, we first need to connect to the Redis server, which is very direct in redis-py. We need to set the decode_responses parameter as true so that we do not get the response in byte format.

import redis
r = redis.Redis(decode_responses=True)
r.ping()
True

Now that we have connected to the Redis server, let’s start performing simple CRUD operations.

To set a key-value pair, we use the “set” function that accepts the key and the value as the parameter. Please note that the key should always be either of string data type or bytes.

r.set('hello', 'world')

To get the value for a specific key, we use the “get” function that accepts the key for which we want the value to be returned.

r.get('hello')
world

To set multiple key-value pairs, we use the “mset” function that stands for multiple-set and accepts multiple key-value pairs as parameters.

data = {
    'hello': 'world',
    'lorem': 'ipsum'
}
r.mset(data)
r.get('lorem')
ipsum

To set a key-value pair where the value is of a set data type, we use the “sadd” function. The set data type contains only unique elements, unlike the list data type. Let’s now store a set of fruits without the fruits being repeated.

fruits = ["avocado",  "strawberry", "strawberry", "mango", "orange"]
r.sadd('fruits', *fruits)

To get all the values of fruits that we just stored, we can use the “smembers” function.

r.smembers('fruits')
{'avocado', 'mango', 'orange', 'strawberry'}

Since we have seen how to store set data type values in Redis, let us now learn to store list data types. It can be done using the “lpush” function. Let us store a list of programming languages using this function.

programming_languages = ['python', 'C#', 'C++', 'C++', 'javascript']
r.lpush('languages', *programming_languages)

To get all the elements in the list, we use the “lrange” function that helps us traverse the elements in the list. The “-1” denotes that the function is expected to return all the elements, but if you want to return only the first 3 elements of the list, you can do so by just replacing “-1” with “2”. Note that it is not “3” because it will traverse till the index is three and return four elements in total.

r.lrange('languages', 0, -1)
['javascript', 'C++', 'C++', 'C#', 'python']
r.lrange('languages', 0, 2)
['javascript', 'C++', 'C++']

Now, let us try to save a nested object in Redis. For storing nested objects, we can make use of the “hset” function but it allows only one level of nesting.

r.hset('person', 'name', 'Ram')
r.hget('person', 'name')
Ram

If you want to store deeply nested objects with different data types, serialization techniques like using json or pickle can be used. Let’s see this in action to better understand.

import json
personal_information = {
    'name': 'Rahul',
    'age': 20,
    'address':{
        'house_no': 189,
        'flat_name': 'Golden Flower',
        'area': 'Guindy'
    },
    'languages_known': ['english', 'hindi', 'tamil']
}
r.set('personal_information', json.dumps(personal_information))

To extract the information stored, we can directly use “get” function and then undo the stringification performed by json.

json.loads(r.get('personal_information'))
{'name': 'Rahul',
 'age': 20,
 'address': {'house_no': 189, 'flat_name': 'Golden Flower', 'area': 'Guindy'},
 'languages_known': ['english', 'hindi', 'tamil']}

Since it is an in-memory data store, it is important that old key-value pairs get deleted or rather expired to make room for storing new data. For this, Redis has the key expiry option available. Let us now try to store a key-value pair with an expiration time. We can make use of the “setex” function to set the expiry for a key-value pair. It accepts the TTL in seconds. If you want to set the TTL in milliseconds, you can use the “psetex” function.

r.setex('lorem', 10, 'ipsum') # 10 seconds
r.psetex('hello', 10, 'world') # 10 milli seconds

To know how much time is remaining for a key to expire, we can use the “ttl” function which will return the time remaining in seconds. Similarly, the “pttl” function will return the same but in milliseconds. If the key has expired, the returned value will be negative.

r.ttl('lorem')
2
r.pttl('lorem')
-2

Suppose we want to check if a key has expired or not, we can make use of the “exists” function that will return 1 if it is available and 0 if it has expired.

r.exists("lorem")
1
r.exists("hello")
0

To delete a key-value pair in Redis, we can use the “delete” function. It accepts the key that you want to delete.

r.delete('lorem')

Conclusion

In this article, we discussed and covered the following:

  • What is Redis?
  • Installing docker on windows
  • Running it on a docker container
  • Connecting using redis-py
  • Performing simple CRUD operations using redis-py

 

The functions discussed in this article are necessary for understanding and performing basic CRUD operations in Redis, but there are a lot of different functions readily available. To learn more about these functions, refer to the official Redis documentation. The official website has a separate page covering all the commands that are available in Redis. You can access that page by clicking on this link. As mentioned earlier, Redis can be an all-in-one database with the introduction of  Stack. If interested, you can learn more about the Stack here. I will try to cover Redis Stack in another article.

That’s it for this article. Hope you enjoyed reading this article and learned something new. Thanks for reading and happy learning!

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Related Courses

image.name
0 Hrs 70 Lessons
5

Introduction to Python

Free

image.name
0 Hrs 13 Lessons
4.94

Introduction to Web Scraping using Python

Free

image.name
0 Hrs 22 Lessons
4.9

Time Series Forecasting using Python

Free

  • [tta_listen_btn class="listen"]