Skip to content

Commit 7d73d74

Browse files
authored
DOC-4197: add TCEs to the geospatial query page (#3378)
1 parent c7483b3 commit 7d73d74

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

doctests/query_geo.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# EXAMPLE: query_geo
2+
# HIDE_START
3+
import json
4+
import sys
5+
import redis
6+
from redis.commands.json.path import Path
7+
from redis.commands.search.field import GeoField, GeoShapeField
8+
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
9+
from redis.commands.search.query import Query
10+
11+
r = redis.Redis(decode_responses=True)
12+
13+
# create index
14+
schema = (
15+
GeoField("$.store_location", as_name="store_location"),
16+
GeoShapeField("$.pickup_zone", coord_system=GeoShapeField.FLAT, as_name="pickup_zone")
17+
)
18+
19+
index = r.ft("idx:bicycle")
20+
index.create_index(
21+
schema,
22+
definition=IndexDefinition(prefix=["bicycle:"], index_type=IndexType.JSON),
23+
)
24+
25+
# load data
26+
with open("data/query_em.json") as f:
27+
bicycles = json.load(f)
28+
29+
pipeline = r.pipeline(transaction=False)
30+
for bid, bicycle in enumerate(bicycles):
31+
pipeline.json().set(f'bicycle:{bid}', Path.root_path(), bicycle)
32+
pipeline.execute()
33+
# HIDE_END
34+
35+
# STEP_START geo1
36+
params_dict = {"lon": -0.1778, "lat": 51.5524, "radius": 20, "units": "mi"}
37+
q = Query("@store_location:[$lon $lat $radius $units]").dialect(2)
38+
res = index.search(q, query_params=params_dict)
39+
print(res)
40+
# >>> Result{1 total, docs: [Document {'id': 'bicycle:5', ...
41+
# REMOVE_START
42+
assert res.total == 1
43+
# REMOVE_END
44+
# STEP_END
45+
46+
# STEP_START geo2
47+
params_dict = {"bike": "POINT(-0.1278 51.5074)"}
48+
q = Query("@pickup_zone:[CONTAINS $bike]").dialect(3)
49+
res = index.search(q, query_params=params_dict)
50+
print(res.total) # >>> 1
51+
# REMOVE_START
52+
assert res.total == 1
53+
# REMOVE_END
54+
# STEP_END
55+
56+
# STEP_START geo3
57+
params_dict = {"europe": "POLYGON((-25 35, 40 35, 40 70, -25 70, -25 35))"}
58+
q = Query("@pickup_zone:[WITHIN $europe]").dialect(3)
59+
res = index.search(q, query_params=params_dict)
60+
print(res.total) # >>> 5
61+
# REMOVE_START
62+
assert res.total == 5
63+
# REMOVE_END
64+
# STEP_END
65+
66+
# REMOVE_START
67+
# destroy index and data
68+
r.ft("idx:bicycle").dropindex(delete_documents=True)
69+
# REMOVE_END

0 commit comments

Comments
 (0)