Skip to main content

How to store JSON documents in Redis with Python

RedisJSON is a source-available Redis module that lets you store, manipulate, and query JSON documents in Redis. The standard Redis Python client (v4.0 or greater) supports all of the features of RedisJSON, and in this tutorial, we'll see how to get started with them.

Step 1. Create a free Cloud account​

Create your free Redis Enterprise Cloud account. Once you click on β€œGet Started”, you will receive an email with a link to activate your account and complete your signup process.

tip

For a limited time, use TIGER200 to get $200 credits on Redis Enterprise Cloud and try all the advanced capabilities!

πŸŽ‰ Click here to sign up

Step 2. Create Your database​

Choose your preferred cloud vendor. Select the region and then click "Let's start free" to create your free database automatically.

tip

If you want to create a custom database with your preferred name and type of redis, click "Create a custom database" option shown in the image.

create database

Step 3. Verify the database details​

You will be provided with Public endpoint URL and "Redis Stack" as the type of database with the list of modules that comes by default.

verify database

Step 4. Using RedisInsight​

RedisInsight is a visual tool that lets you do both GUI- and CLI-based interactions with your Redis database, and so much more when developing your Redis based application. It is a fully-featured pure Desktop GUI client that provides capabilities to design, develop and optimize your Redis application. It works with any cloud provider as long as you run it on a host with network access to your cloud-based Redis server. It makes it easy to discover cloud databases and configure connection details with a single click. It allows you to automatically add Redis Enterprise Software and Redis Enterprise Cloud databases.

Follow this link to install RedisInsight v2 on your local system. Assuming that you already have RedisInsight v2 installed on your MacOS, you can browse through the Applications and click "RedisInsight-v2" to bring up the Redis Desktop GUI tool.

Step 5. Add Redis database​

access redisinsight

Step 6. Enter Redis Enterprise Cloud details​

Add the Redis Enterprise cloud database endpoint, port and password.

access redisinsight

Step 7. Verify the database under RedisInsight dashboard​

database details

Storing JSON in Redis​

Let's consider a simple JSON document structure representing a user:

 {
"name": "Jane",
"age": 33,
"location: "Chawton"
}

Installing Redis​

 $ pip3 install redis
Collecting redis
Downloading redis-4.2.0-py3-none-any.whl (225 kB)
Collecting async-timeout>=4.0.2
Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)
Collecting typing-extensions
Downloading typing_extensions-4.1.1-py3-none-any.whl (26 kB)
..
Requirement already satisfied: packaging>=20.4 in /usr/lib/python3.8/site-packages (from redis) (20.4)
Collecting wrapt<2,>=1.10
Installing collected packages: async-timeout, typing-extensions, wrapt, deprecated, redis
Running setup.py install for wrapt ... done
Successfully installed async-timeout-4.0.2 deprecated-1.2.13 redis-4.2.0 typing-extensions-4.1.1 wrapt-1.14.0

Here's the Python code to store this document in Redis using RedisJSON:

import redis
from redis.commands.json.path import Path

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

jane = {
'name': "Jane",
'Age': 33,
'Location': "Chawton"
}

client.json().set('person:1', '$', jane)

result = client.json().get('person:1')
print(result)

In the code above, we first connect to Redis and store a reference to the connection in the client variable.

Next, we create a Python dictionary to represent a person object.

And finally, we store the object in Redis using the json().set() method. The first argument, person:1 is the name of the key that will reference the JSON. The second argument is a JSON path. We use $, as this is a new object. Finally, we pass in the Python dictionary, which will be serialized to JSON.

To retrieve the JSON object, we run json().get(), passing in the key. The result is a Python dictionary representing the JSON object stored in Redis.

Run the code​

If you copy the code above into a file called main.py, you can run the code like so:

$ pipenv python run main.py

Verify that the JSON document has been added to Redis​

Start redis-cli to connect to your Redis instance. Then run the following command:

localhost:6379> json.get person:1
"{\"name\":\"Jane\",\"Age\":33,\"Location\":\"Chawton\"}"

Fetching specific fields from a JSON document​

You can use RedisJSON to fetch specific fields from a document by specifying a path. For example, here's how to return only the name field:

name = client.json().get('person:1', Path('.name'))
print(name)

This code will print the string "Jane".

You can execute the same query from the command line:

localhost:6379> json.get person:1 '.name'
"\"Jane\""

References​