Skip to content

Commit e4dbdc6

Browse files
author
Kyle Banker
committed
Update Python/RedisJSON tutorial
1 parent bbcf30f commit e4dbdc6

File tree

1 file changed

+59
-77
lines changed

1 file changed

+59
-77
lines changed

docs/howtos/redisjson/using-python/index-usingpython.mdx

Lines changed: 59 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -3,138 +3,120 @@ id: index-usingpython
33
title: How to store JSON documents in Redis with Python
44
sidebar_label: RedisJSON and Python
55
slug: /howtos/redisjson/using-python
6-
authors: [ajeet]
76
---
87

8+
[RedisJSON](https://oss.redis.com/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 feature of RedisJSON, and in this tutorial, we'll see how to use them.
99

10-
RedisJSON is a Redis module that lets you store JSON documents in Redis. It is a JSON data type for Redis that lets you to fetch or modify a specific element in the document tree, without retrieving (or internally even parsing) the document. Its Python client even lets you store python dicts and convert them to JSON automatically.
10+
## Getting started with RedisJSON
1111

12-
### RedisJSON Python Client
13-
14-
15-
The 'rejson-py' is a package that allows storing, updating and querying objects as JSON documents in a Redis database that is extended with the RedisJSON module. The package extends redis-py's interface with RedisJSON's API, and performs on-the-fly serialization/deserialization of objects to/from JSON.
16-
17-
Follow the steps below to get started with RedisJSON with Python:
18-
19-
20-
### Step 1. Run RedisJSON Docker container
12+
To run the examples below, you'll need to ensure that you have an instance of Redis that includes RedisJSON. If you're developing locally, you can use Docker for this:
2113

2214
```bash
2315
docker run -p 6379:6379 --name redis-redisjson redislabs/rejson:latest
2416
```
2517

18+
## Verify that the RedisJSON module is loaded
2619

27-
### Step 2. Verify if RedisJSON module is loaded
20+
Connect to Redis using `redis-cli`, and run the `info modules` command:
2821

2922
```bash
3023
redis-cli
3124
127.0.0.1:6379> info modules
3225
# Modules
33-
module:name=ReJSON,ver=10007,api=1,filters=0,usedby=[],using=[],options=[]
26+
module:name=ReJSON,ver=20004,api=1,filters=0,usedby=[],using=[],options=[]
3427
127.0.0.1:6379>
3528
```
3629

37-
### Step 3. Storing the JSON document
30+
Ensure that you're running RedisJSON v2.0 or greater (here indicated as `20004`).
31+
32+
## Load the latest version of `redis-py`
3833

39-
Let us consider a simple JSON document structure:
34+
You'll need `redis-py` version 4.0 or later. If you're using `pipenv`, you can install the client library like so:
4035

4136
```
42-
employee
43-
{
44-
"name": "Paul John",
45-
"age": 25,
46-
"location: "USA"
47-
}
37+
pipenv install redis
4838
```
4939

50-
Below is a python code to store the JSON document into Redis:
40+
Then you can run `pipenv graph` to make sure you're running the latest version of the client:
5141

52-
```python
53-
from rejson import Client, Path
54-
55-
56-
rj = Client(host='localhost', port=6379, decode_responses=True)
57-
58-
employee = {
59-
60-
'name': "Paul",
61-
'Age': '25',
62-
'Location': "USA"
63-
}
64-
rj.jsonset('employee', Path.rootPath(), employee)
42+
```
43+
$ pipenv graph
44+
redis==4.0.2
6545
```
6646

67-
In the code above, we use JSON.GET to extract the JSON elements. Save the above file as "employee.py".
47+
## Storing JSON in Redis
6848

69-
### Step 4. Load Redis Module
49+
Let's consider a simple JSON document structure representing a user:
7050

71-
```bash
72-
pip install rejson
7351
```
74-
75-
### Step 5. Execute the python script
76-
77-
```bash
78-
python3 employee.py
52+
{
53+
"name": "Jane",
54+
"age": 25,
55+
"location: "USA"
56+
}
7957
```
8058

81-
### Step 6. Verify the JSON document added to Redis
59+
Here's the Python code to store this document in Redis using RedisJSON:
8260

61+
```python
62+
import redis
63+
from redis.commands.json.path import Path
8364

84-
<b>Command</b>:
65+
client = redis.Redis(host='localhost', port=6379, db=0)
8566

86-
```bash
87-
127.0.0.1:6379> JSON.GET employee
88-
```
67+
jane = {
68+
'name': "Jane",
69+
'Age': 33,
70+
'Location': "Chawton"
71+
}
8972

90-
<b>Result</b>:
73+
client.json().set('person:1', Path.rootPath(), jane)
9174

92-
```
93-
"{\"name\":\"Paul\",\"Age\":\"25\",\"Location\":\"USA\"}"
94-
127.0.0.1:6379>
75+
result = client.json().get('person:1')
76+
print(result)
9577
```
9678

97-
### Step 7. Fetching the specific fields within JSON document
79+
In the code above, we first connect to Redis and store a reference to the connection in the `client` variable.
9880

99-
It's possible to fetch specific field within JSON element. Let us modify the above code and add "address" field as shown below:
81+
Next, we create a Python dictionary to represent a person object.
10082

101-
```python
102-
from rejson import Client, Path
83+
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 store the JSON. The second argument is a JSON path. We use `Path.rootPath()`, as this is a new object. Finally, we pass in the Python dictionary, which will be serialized to JSON.
10384

85+
To retrieve the JSON object, we run `json().get()`, passing the key. The result is the Python dictionary we passed in.
10486

105-
rj = Client(host='localhost', port=6379, decode_responses=True)
87+
### Run the code
10688

107-
employee = {
108-
109-
'name': "Paul",
110-
'Age': '25',
111-
'address': {
112-
'location': "USA"
113-
}
114-
}
115-
rj.jsonset('employee', Path.rootPath(), employee)
116-
rj.jsonget('employee', Path('.address.location'))
117-
```
118-
119-
In the above example, the code tries to fetch only the location under the address field.
89+
If you copy the code above in a file called `main.py`, you can run the code like so:
12090

91+
```bash
92+
$ pipenv python run main.py
12193

122-
### Step 8. Verifying the results
12394

95+
## Verify that the JSON document has been added to Redis
12496

125-
<b>Command</b>:
97+
Start `redis-cli` to connect to your Redis instance. The run the following command:
12698

12799
```bash
128-
127.0.0.1:6379> JSON.GET employee .address.location
100+
localhost:6379> json.get person:1
101+
"{\"name\":\"Jane\",\"Age\":33,\"Location\":\"Chawton\"}"
129102
```
130103

104+
## Fetching the specific fields within a JSON document
131105

132-
<b>Results</b>:
106+
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:
133107
108+
```python
109+
name = client.json().get('person:1', Path('.name'))
110+
print(name)
134111
```
135-
"\"USA\""
136-
```
112+
This code will print the string "Jane".
113+
114+
You can execute the same query from the command line:
137115
116+
```bash
117+
localhost:6379> json.get person:1 '.name'
118+
"\"Jane\""
119+
```
138120
139121
### References
140122

0 commit comments

Comments
 (0)