Skip to content

Commit 5038e93

Browse files
Merge pull request #2276 from redis/DOC-5821-python-query-notebook
DOC-5821 Python index/query notebook link
2 parents ecf677a + 7ddb847 commit 5038e93

File tree

2 files changed

+207
-3
lines changed

2 files changed

+207
-3
lines changed

content/develop/clients/redis-py/queryjson.md

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,14 @@ to learn more about the available connection options.
6464
{{< clients-example py_home_json connect >}}
6565
{{< /clients-example >}}
6666

67+
The example uses an index called `idx:users` for JSON documents and adds
68+
some JSON documents with the `user:` key prefix. To avoid errors, first
69+
delete any existing index or documents whose names that might
70+
conflict with the example:
71+
72+
{{< clients-example py_home_json cleanup_json >}}
73+
{{< /clients-example >}}
74+
6775
Create an index for the JSON data. The code below specifies that only JSON documents with
6876
the key prefix `user:` are indexed. For more information, see
6977
[Query syntax]({{< relref "/develop/ai/search-and-query/query/" >}}).
@@ -111,9 +119,16 @@ need to specify some slightly different options.
111119
When you create the schema for a hash index, you don't need to
112120
add aliases for the fields, since you use the basic names to access
113121
the fields anyway. Also, you must use `HASH` for the `IndexType`
114-
when you create the index. The code below shows these changes with
115-
a new index called `hash-idx:users`, which is otherwise the same as
116-
the `idx:users` index used for JSON documents in the previous examples.
122+
when you create the index.
123+
124+
First delete any existing index or documents
125+
whose names might conflict with the hash example:
126+
127+
{{< clients-example py_home_json cleanup_hash >}}
128+
{{< /clients-example >}}
129+
130+
Create a new index called `hash-idx:users`, which is otherwise the same as
131+
the `idx:users` index used for JSON documents in the previous examples:
117132

118133
{{< clients-example py_home_json make_hash_index >}}
119134
{{< /clients-example >}}
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
# EXAMPLE: py_home_json
2+
# BINDER_ID python-py_home_json
3+
"""
4+
JSON examples from redis-py "home" page"
5+
https://redis.io/docs/latest/develop/connect/clients/python/redis-py/#example-indexing-and-querying-json-documents
6+
"""
7+
8+
# STEP_START import
9+
import redis
10+
from redis.commands.json.path import Path
11+
import redis.commands.search.aggregation as aggregations
12+
import redis.commands.search.reducers as reducers
13+
from redis.commands.search.field import TextField, NumericField, TagField
14+
from redis.commands.search.index_definition import IndexDefinition, IndexType
15+
from redis.commands.search.query import Query
16+
import redis.exceptions
17+
# STEP_END
18+
19+
# STEP_START create_data
20+
user1 = {
21+
"name": "Paul John",
22+
"email": "[email protected]",
23+
"age": 42,
24+
"city": "London"
25+
}
26+
27+
user2 = {
28+
"name": "Eden Zamir",
29+
"email": "[email protected]",
30+
"age": 29,
31+
"city": "Tel Aviv"
32+
}
33+
34+
user3 = {
35+
"name": "Paul Zamir",
36+
"email": "[email protected]",
37+
"age": 35,
38+
"city": "Tel Aviv"
39+
}
40+
# STEP_END
41+
42+
# STEP_START connect
43+
r = redis.Redis(decode_responses=True)
44+
# STEP_END
45+
46+
# STEP_START cleanup_json
47+
try:
48+
r.ft("idx:users").dropindex(True)
49+
except redis.exceptions.ResponseError:
50+
pass
51+
52+
r.delete("user:1", "user:2", "user:3")
53+
# STEP_END
54+
55+
# STEP_START make_index
56+
schema = (
57+
TextField("$.name", as_name="name"),
58+
TagField("$.city", as_name="city"),
59+
NumericField("$.age", as_name="age")
60+
)
61+
62+
indexCreated = r.ft("idx:users").create_index(
63+
schema,
64+
definition=IndexDefinition(
65+
prefix=["user:"], index_type=IndexType.JSON
66+
)
67+
)
68+
# STEP_END
69+
# REMOVE_START
70+
assert indexCreated
71+
# REMOVE_END
72+
73+
# STEP_START add_data
74+
user1Set = r.json().set("user:1", Path.root_path(), user1)
75+
user2Set = r.json().set("user:2", Path.root_path(), user2)
76+
user3Set = r.json().set("user:3", Path.root_path(), user3)
77+
# STEP_END
78+
# REMOVE_START
79+
assert user1Set
80+
assert user2Set
81+
assert user3Set
82+
# REMOVE_END
83+
84+
# STEP_START query1
85+
findPaulResult = r.ft("idx:users").search(
86+
Query("Paul @age:[30 40]")
87+
)
88+
89+
print(findPaulResult)
90+
# >>> Result{1 total, docs: [Document {'id': 'user:3', ...
91+
# STEP_END
92+
# REMOVE_START
93+
assert str(findPaulResult) == (
94+
"Result{1 total, docs: [Document {'id': 'user:3', 'payload': None, "
95+
+ "'json': '{\"name\":\"Paul Zamir\",\"email\":"
96+
+ "\"[email protected]\",\"age\":35,\"city\":\"Tel Aviv\"}'}]}"
97+
)
98+
# REMOVE_END
99+
100+
# STEP_START query2
101+
citiesResult = r.ft("idx:users").search(
102+
Query("Paul").return_field("$.city", as_field="city")
103+
).docs
104+
105+
print(citiesResult)
106+
# >>> [Document {'id': 'user:1', 'payload': None, ...
107+
# STEP_END
108+
# REMOVE_START
109+
citiesResult.sort(key=lambda doc: doc['id'])
110+
111+
assert str(citiesResult) == (
112+
"[Document {'id': 'user:1', 'payload': None, 'city': 'London'}, "
113+
+ "Document {'id': 'user:3', 'payload': None, 'city': 'Tel Aviv'}]"
114+
)
115+
# REMOVE_END
116+
117+
# STEP_START query3
118+
req = aggregations.AggregateRequest("*").group_by(
119+
'@city', reducers.count().alias('count')
120+
)
121+
122+
aggResult = r.ft("idx:users").aggregate(req).rows
123+
print(aggResult)
124+
# >>> [['city', 'London', 'count', '1'], ['city', 'Tel Aviv', 'count', '2']]
125+
# STEP_END
126+
# REMOVE_START
127+
aggResult.sort(key=lambda row: row[1])
128+
129+
assert str(aggResult) == (
130+
"[['city', 'London', 'count', '1'], ['city', 'Tel Aviv', 'count', '2']]"
131+
)
132+
# REMOVE_END
133+
134+
# STEP_START cleanup_hash
135+
try:
136+
r.ft("hash-idx:users").dropindex(True)
137+
except redis.exceptions.ResponseError:
138+
pass
139+
140+
r.delete("huser:1", "huser:2", "huser:3")
141+
# STEP_END
142+
143+
# STEP_START make_hash_index
144+
hashSchema = (
145+
TextField("name"),
146+
TagField("city"),
147+
NumericField("age")
148+
)
149+
150+
hashIndexCreated = r.ft("hash-idx:users").create_index(
151+
hashSchema,
152+
definition=IndexDefinition(
153+
prefix=["huser:"], index_type=IndexType.HASH
154+
)
155+
)
156+
# STEP_END
157+
# REMOVE_START
158+
assert hashIndexCreated
159+
# REMOVE_END
160+
161+
# STEP_START add_hash_data
162+
huser1Set = r.hset("huser:1", mapping=user1)
163+
huser2Set = r.hset("huser:2", mapping=user2)
164+
huser3Set = r.hset("huser:3", mapping=user3)
165+
# STEP_END
166+
# REMOVE_START
167+
assert huser1Set
168+
assert huser2Set
169+
assert huser3Set
170+
# REMOVE_END
171+
172+
# STEP_START query1_hash
173+
findPaulHashResult = r.ft("hash-idx:users").search(
174+
Query("Paul @age:[30 40]")
175+
)
176+
177+
print(findPaulHashResult)
178+
# >>> Result{1 total, docs: [Document {'id': 'huser:3',
179+
# >>> 'payload': None, 'name': 'Paul Zamir', ...
180+
# STEP_END
181+
# REMOVE_START
182+
assert str(findPaulHashResult) == (
183+
"Result{1 total, docs: [Document " +
184+
"{'id': 'huser:3', 'payload': None, 'name': 'Paul Zamir', " +
185+
"'email': '[email protected]', 'age': '35', 'city': 'Tel Aviv'}]}"
186+
)
187+
# REMOVE_END
188+
189+
r.close()

0 commit comments

Comments
 (0)