
本文深入探讨了使用Python客户端操作Redisearch时,进行全文索引前缀查询的常见问题及解决方案。重点阐述了Redisearch前缀查询的匹配规则、最小字符长度限制,并提供了正确的查询语法,包括通配符使用和字段限定查询,旨在帮助开发者高效地实现实时搜索功能。
Redisearch是一个高性能的全文搜索引擎,它与Redis结合,提供实时索引和查询功能。通过Python客户端redis-py,开发者可以方便地创建索引、导入数据并执行复杂的搜索查询。
首先,我们需要导入必要的库并准备一些示例数据:
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, NumericField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
# 示例数据
d1 = {"key": "shahrukh khan", "pl": '{"d": "mvtv", "id": "1234-a", "img": "foo.jpg", "t": "act", "tme": "1965-"}', "org": "1", "p": 100}
d2 = {"key": "salman khan", "pl": '{"d": "mvtv", "id": "1236-a", "img": "fool.jpg", "t": "act", "tme": "1965-"}', "org": "1", "p": 100}
d3 = {"key": "aamir khan", "pl": '{"d": "mvtv", "id": "1237-a", "img": "fooler.jpg", "t": "act", "tme": "1965-"}', "org": "1", "p": 100}
# 定义索引模式
# TextField("$.key", as_name="key") 表示将JSON路径$.key的值索引为名为"key"的文本字段
# NumericField("$.p", as_name="p") 表示将JSON路径$.p的值索引为名为"p"的数字字段
schema = (
TextField("$.key", as_name="key"),
NumericField("$.p", as_name="p"),
)
# 连接Redis并初始化Redisearch客户端
r = redis.Redis(host='localhost', port=6379)
rs = r.ft("idx:au") # 使用索引名称 "idx:au"
# 创建索引
# IndexDefinition 指定了索引的前缀和类型
# prefix=["au:"] 表示只有key以"au:"开头的文档才会被索引
# index_type=IndexType.JSON 表示索引的是JSON文档
try:
rs.create_index(
schema,
definition=IndexDefinition(
prefix=["au:"], index_type=IndexType.JSON
)
)
print("索引 'idx:au' 创建成功或已存在。")
except Exception as e:
# 如果索引已存在,Redisearch会抛出错误,这里捕获并忽略
if "Index already exists" not in str(e):
raise e
print("索引 'idx:au' 已存在,跳过创建。")
# 导入数据
# 使用 r.json().set 将JSON数据存储到Redis中,key前缀需与索引定义匹配
r.json().set("au:mvtv-1234-a", Path.root_path(), d1)
r.json().set("au:mvtv-1236-a", Path.root_path(), d2)
r.json().set("au:mvtv-1237-a", Path.root_path(), d3)
print("数据导入完成。")在使用Redisearch进行前缀查询时,开发者常会遇到查询结果为空的问题。例如,尝试使用Query("s")来查找所有以"s"开头的文档,但实际却返回空集。
立即学习“Python免费学习笔记(深入)”;
# 错误的查询示例:期望查找以"s"开头的文档,但会返回空集
result_s = rs.search(Query("s"))
print(f"查询 's' 的结果: {result_s.total} 条文档")核心原因分析:
了解了上述限制后,我们可以采用正确的策略来执行前缀查询。
为了进行前缀查询,我们需要在至少两个字符的前缀后加上*。例如,要查找以"sa"开头的文档,可以使用Query("sa*"):
# 正确的前缀查询示例:查找以"sa"开头的文档
result_sa_prefix = rs.search(Query("sa*"))
print(f"\n查询 'sa*' 的结果: {result_sa_prefix.total} 条文档")
for doc in result_sa_prefix.docs:
print(f"ID: {doc.id}, JSON: {doc.json}")执行上述代码,您将看到返回了包含"salman khan"的文档,因为"salman"以"sa"开头。
默认情况下,Query()会在所有TextField类型的字段中进行搜索。如果您希望将搜索范围限定在特定的字段,可以使用@field_name:word的语法。
例如,要在key字段中查找以"sa"开头的文档:
# 限定字段的前缀查询示例:在"key"字段中查找以"sa"开头的文档
result_key_sa_prefix = rs.search(Query("@key:sa*"))
print(f"\n查询 '@key:sa*' 的结果: {result_key_sa_prefix.total} 条文档")
for doc in result_key_sa_prefix.docs:
print(f"ID: {doc.id}, JSON: {doc.json}")这同样会返回"salman khan"的文档,但查询效率可能更高,尤其是在索引包含大量字段时。
下面是整合了创建索引、导入数据和正确查询方法的完整代码示例:
import redis
from redis.commands.json.path import Path
from redis.commands.search.field import TextField, NumericField
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.query import Query
# 示例数据
d1 = {"key": "shahrukh khan", "pl": '{"d": "mvtv", "id": "1234-a", "img": "foo.jpg", "t": "act", "tme": "1965-"}', "org": "1", "p": 100}
d2 = {"key": "salman khan", "pl": '{"d": "mvtv", "id": "1236-a", "img": "fool.jpg", "t": "act", "tme": "1965-"}', "org": "1", "p": 100}
d3 = {"key": "aamir khan", "pl": '{"d": "mvtv", "id": "1237-a", "img": "fooler.jpg", "t": "act", "tme": "1965-"}', "org": "1", "p": 100}
# 定义索引模式
schema = (
TextField("$.key", as_name="key"),
NumericField("$.p", as_name="p"),
)
# 连接Redis并初始化Redisearch客户端
r = redis.Redis(host='localhost', port=6379, decode_responses=True) # decode_responses=True 可以让结果直接是字符串
rs = r.ft("idx:au")
# 创建索引
try:
rs.create_index(
schema,
definition=IndexDefinition(
prefix=["au:"], index_type=IndexType.JSON
)
)
print("索引 'idx:au' 创建成功。")
except Exception as e:
if "Index already exists" in str(e):
print("索引 'idx:au' 已存在,跳过创建。")
else:
raise e
# 导入数据
r.json().set("au:mvtv-1234-a", Path.root_path(), d1)
r.json().set("au:mvtv-1236-a", Path.root_path(), d2)
r.json().set("au:mvtv-1237-a", Path.root_path(), d3)
print("数据导入完成。")
# 错误查询示例:单字符查询,会返回空集
print("\n--- 错误查询示例 ---")
result_s = rs.search(Query("s"))
print(f"查询 's' 的结果: {result_s.total} 条文档")
if result_s.total > 0:
for doc in result_s.docs:
print(f"ID: {doc.id}, JSON: {doc.json}")
# 正确查询示例1:使用通配符进行前缀查询 (至少两个字符)
print("\n--- 正确查询示例1:通用前缀查询 ---")
result_sa_prefix = rs.search(Query("sa*"))
print(f"查询 'sa*' 的结果: {result_sa_prefix.total} 条文档")
if result_sa_prefix.total > 0:
for doc in result_sa_prefix.docs:
print(f"ID: {doc.id}, JSON: {doc.json}")
# 正确查询示例2:限定字段范围的前缀查询
print("\n--- 正确查询示例2:限定字段前缀查询 ---")
result_key_sa_prefix = rs.search(Query("@key:sa*"))
print(f"查询 '@key:sa*' 的结果: {result_key_sa_prefix.total} 条文档")
if result_key_sa_prefix.total > 0:
for doc in result_key_sa_prefix.docs:
print(f"ID: {doc.id}, JSON: {doc.json}")
# 清理:删除索引 (可选)
# try:
# rs.dropindex()
# print("\n索引 'idx:au' 已删除。")
# except Exception as e:
# print(f"\n删除索引失败: {e}")在使用Redisearch进行全文索引和前缀查询时,请牢记以下几点:
通过遵循这些指南,您可以有效地利用Redisearch的强大功能,在Python应用程序中实现高效、准确的实时全文搜索。
以上就是Redisearch Python客户端全文索引前缀查询指南与常见问题解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号