Running Redis on Google Colab

Because of the increasing use of Redis for data science and machine learning, it is handy to run Redis directly from a Google Colab notebook.  However, running Redis on Google Colab differs from how you would set it up on your local machine or using Docker. In this post, I show you how you can run Redis on your Colab notebook, in two simple steps, directly from your browser.

Google Colab is a popular browser-based environment for executing Python code on hosted Jupyter notebooks and training models for machine learning (ML), including free access to GPUs. It is a platform for data scientists and machine learning (ML) engineers to help them learn and develop ML models in Python. Redis is an in-memory open source database that is increasingly being used in machine learning – from caching, messaging and fast data ingest, to semantic search and online feature stores.

An image with Redis and Colab logos

Step 1: Installation

While Jupyter Notebooks support many languages, Colab supports only Python. To use Redis with Python, you need a Redis Python client. In this tutorial, we demonstrate the use of redis-py, a Redis Python client, which we install using the %pip install redis command. 

You can run a shell command in Jupyter Notebook or Google Colab with IPython by prefixing it with the ! character or % to use magic commands. A list of useful magic commands for data scientists is described in Top 8 magic commands in Jupyter Notebook.

To install Redis and the Redis Python client:

!curl -fsSL -o redis-stack-server.tar.gz 
!tar -xvf redis-stack-server.tar.gz
!pip install redis

Step 2: Start the Redis Server

To start the Redis server run:

!./redis-stack-server-6.2.6-v7/bin/redis-stack-server --daemonize yes

That’s it! It’s that simple.

Connecting to the Redis server and Redis command functions

Let’s now look at the commands we need to verify that Redis is running, connect to it, and read and write data. 

To verify that Redis is up and running, create a connection to Redis using the Python client redis-py and then ping the server:

import redis
client = redis.Redis(host = 'localhost', port=6379)

If you get a response True, then you are good to go!

Once you are connected to Redis, you can read and write data with Redis command functions. In this example, we use Redis as a key value database (also called key value store). The following code snippet assigns the value bar to the Redis key foo, reads it back, and returns it:

client.set('foo', 'bar')

If you want to play with the commands yourself, consult the Redis with Colab notebook, which includes the code in this tutorial.