1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
# EXAMPLE: query_em
# HIDE_START
import json
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, NumericField, TagField
from redis.commands.search.index_definition import IndexDefinition, IndexType
from redis.commands.search.query import NumericFilter, Query
r = redis.Redis(decode_responses=True)
# create index
schema = (
TextField("$.description", as_name="description"),
NumericField("$.price", as_name="price"),
TagField("$.condition", as_name="condition"),
)
index = r.ft("idx:bicycle")
index.create_index(
schema,
definition=IndexDefinition(prefix=["bicycle:"], index_type=IndexType.JSON),
)
# load data
with open("data/query_em.json") as f:
bicycles = json.load(f)
pipeline = r.pipeline(transaction=False)
for bid, bicycle in enumerate(bicycles):
pipeline.json().set(f'bicycle:{bid}', Path.root_path(), bicycle)
pipeline.execute()
# HIDE_END
# STEP_START em1
res = index.search(Query("@price:[270 270]"))
print(res.total)
# >>> 1
# REMOVE_START
assert res.total == 1
# REMOVE_END
try:
res = index.search(Query("@price:[270]")) # not yet supported in redis-py
print(res.total)
# >>> 1
assert res.total == 1
except:
print("'@price:[270]' syntax not yet supported.")
try:
res = index.search(Query("@price==270")) # not yet supported in redis-py
print(res.total)
# >>> 1
assert res.total == 1
except:
print("'@price==270' syntax not yet supported.")
query = Query("*").add_filter(NumericFilter("price", 270, 270))
res = index.search(query)
print(res.total)
# >>> 1
# REMOVE_START
assert res.total == 1
# REMOVE_END
# STEP_END
# STEP_START em2
res = index.search(Query("@condition:{new}"))
print(res.total)
# >>> 5
# REMOVE_START
assert res.total == 5
# REMOVE_END
# STEP_END
# STEP_START em3
schema = (
TagField("$.email", as_name="email")
)
idx_email = r.ft("idx:email")
idx_email.create_index(
schema,
definition=IndexDefinition(prefix=["key:"], index_type=IndexType.JSON),
)
r.json().set('key:1', Path.root_path(), '{"email": "test@redis.com"}')
try:
res = idx_email.search(Query("test@redis.com").dialect(2))
print(res)
except:
print("'test@redis.com' syntax not yet supported.")
# REMOVE_START
r.ft("idx:email").dropindex(delete_documents=True)
# REMOVE_END
# STEP_END
# STEP_START em4
res = index.search(Query("@description:\"rough terrain\""))
print(res.total)
# >>> 1 (Result{1 total, docs: [Document {'id': 'bicycle:8'...)
# REMOVE_START
assert res.total == 1
# REMOVE_END
# STEP_END
# REMOVE_START
# destroy index and data
r.ft("idx:bicycle").dropindex(delete_documents=True)
# REMOVE_END
|