示例 - 索引和查询JSON文档

学习如何使用Redis查询引擎与JSON

此示例展示了如何为JSON数据创建搜索索引并针对该索引运行查询。

确保你已经安装了Redis Stack和redis-py

导入依赖项:

import redis
from redis.commands.json.path import Path
import redis.commands.search.aggregation as aggregations
import redis.commands.search.reducers as reducers
from redis.commands.search.field import TextField, NumericField, TagField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import NumericFilter, Query

连接到您的Redis数据库。

r = redis.Redis(host='localhost', port=6379)

让我们创建一些测试数据添加到您的数据库中。

user1 = {
    "name": "Paul John",
    "email": "paul.john@example.com",
    "age": 42,
    "city": "London"
}
user2 = {
    "name": "Eden Zamir",
    "email": "eden.zamir@example.com",
    "age": 29,
    "city": "Tel Aviv"
}
user3 = {
    "name": "Paul Zamir",
    "email": "paul.zamir@example.com",
    "age": 35,
    "city": "Tel Aviv"
}

使用schema定义索引字段及其数据类型。使用JSON路径表达式将特定的JSON元素映射到模式字段。

schema = (
    TextField("$.name", as_name="name"), 
    TagField("$.city", as_name="city"), 
    NumericField("$.age", as_name="age")
)

创建一个索引。在这个例子中,所有带有键前缀 user: 的 JSON 文档都将被索引。更多信息,请参阅 查询语法

rs = r.ft("idx:users")
rs.create_index(
    schema,
    definition=IndexDefinition(
        prefix=["user:"], index_type=IndexType.JSON
    )
)
# b'OK'

使用 JSON.SET 在指定路径设置每个用户的值。

r.json().set("user:1", Path.root_path(), user1)
r.json().set("user:2", Path.root_path(), user2)
r.json().set("user:3", Path.root_path(), user3)

让我们找到用户 Paul 并按年龄过滤结果。

res = rs.search(
    Query("Paul @age:[30 40]")
)
# Result{1 total, docs: [Document {'id': 'user:3', 'payload': None, 'json': '{"name":"Paul Zamir","email":"paul.zamir@example.com","age":35,"city":"Tel Aviv"}'}]}

使用JSON路径表达式进行查询。

rs.search(
    Query("Paul").return_field("$.city", as_field="city")
).docs
# [Document {'id': 'user:1', 'payload': None, 'city': 'London'}, Document {'id': 'user:3', 'payload': None, 'city': 'Tel Aviv'}]

使用FT.AGGREGATE聚合您的结果。

req = aggregations.AggregateRequest("*").group_by('@city', reducers.count().alias('count'))
print(rs.aggregate(req).rows)
# [[b'city', b'Tel Aviv', b'count', b'2'], [b'city', b'London', b'count', b'1']]
RATE THIS PAGE
Back to top ↑