Skip to content

Commit ed45c0c

Browse files
DOC-5821 updated existing example
1 parent 712f0e0 commit ed45c0c

File tree

2 files changed

+206
-3
lines changed

2 files changed

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

0 commit comments

Comments
 (0)