Redis®*: 示例:Python 使用方法
本文件是搜索与 JSON指南的一部分。您可以在这里查看完整指南:使用 Redis 查询引擎高效存储和查询 JSON 文档。
👋 欢迎来到 Stackhero 文档!
Stackhero 提供即开即用的 Redis cloud 解决方案,带来多项优势,包括:
- 集成
Redis Commander网页界面。- 无限制的消息大小与传输。
- 只需一键即可轻松完成更新。
- 依托专属私有基础设施,实现卓越性能与强大安全性。
节省时间,简化您的工作流程:只需 5 分钟即可体验 Stackhero 的 Redis cloud hosting 方案!
import os
import redis
from redis.commands.search.field import TextField, TagField, NumericField
from redis.commands.search.index_definition import IndexDefinition, IndexType
from redis.commands.search.query import Query
r = redis.from_url(os.environ['STACKHERO_REDIS_URL_TLS'], decode_responses=True)
# 启动时创建索引
try:
r.ft('productsIndex').create_index(
(
TextField('$.name', as_name='name'),
TagField('$.brand', as_name='brand'),
NumericField('$.price', as_name='price', sortable=True),
),
definition=IndexDefinition(prefix=['product:'], index_type=IndexType.JSON),
)
except redis.ResponseError as error:
if 'Index already exists' not in str(error):
raise
r.json().set('product:1', '$', {
'name': 'Espresso machine',
'brand': 'Bianca',
'price': 459,
})
results = r.ft('productsIndex').search(Query('@name:(espresso) @price:[0 500]'))
print(results.total, results.docs)