当前版本redis-py客户端是否支持Redis Search、Redis JSON及查询示例?
redis-py 对Redis Search、Redis JSON的支持说明
- 4.0及以上版本的官方redis-py已经原生内置了Redis Search和Redis JSON两个模块的完整操作接口,无需额外安装第三方扩展
- 完全支持针对Redis JSON格式存储的数据执行Redis Search查询,仅需要在创建搜索索引时指定索引类型为JSON即可
使用示例
前置依赖
- Redis服务端需部署Redis Stack,或单独安装Redis Search、Redis JSON模块
- 安装对应版本的redis-py:
pip install redis>=4.0.0
示例代码
import redis from redis.commands.search.field import TextField, NumericField from redis.commands.search.indexDefinition import IndexDefinition, IndexType from redis.commands.search.query import Query # 初始化Redis连接,根据实际情况修改连接参数 redis_client = redis.Redis( host="127.0.0.1", port=6379, decode_responses=True ) # 1. 创建JSON专属的搜索索引 try: redis_client.ft("idx:user_json").create_index( fields=[ TextField("$.username", as_name="username"), NumericField("$.age", as_name="age"), TextField("$.location.city", as_name="city") ], definition=IndexDefinition( prefix=["userinfo:"], # 仅索引key前缀为userinfo:的JSON数据 index_type=IndexType.JSON ) ) except Exception as e: if "Index already exists" not in str(e): raise # 2. 写入测试JSON数据 redis_client.json().set("userinfo:1", "$", {"username": "王磊", "age": 27, "location": {"city": "广州"}}) redis_client.json().set("userinfo:2", "$", {"username": "李娜", "age": 31, "location": {"city": "深圳"}}) redis_client.json().set("userinfo:3", "$", {"username": "王小强", "age": 24, "location": {"city": "广州"}}) redis_client.json().set("userinfo:4", "$", {"username": "张亮", "age": 35, "location": {"city": "北京"}}) # 3. 执行搜索查询:查询居住在广州、年龄小于30的用户 search_query = Query("@city:广州 @age:[0 30]") result = redis_client.ft("idx:user_json").search(search_query) # 4. 输出结果 print(f"共匹配到{result.total}条数据:") for item in result.docs: print(f"数据key:{item.id},内容:{item.json}")
运行输出示例
共匹配到2条数据: 数据key:userinfo:1,内容:{"username":"王磊","age":27,"location":{"city":"广州"}} 数据key:userinfo:3,内容:{"username":"王小强","age":24,"location":{"city":"广州"}}
内容的提问来源于stack exchange,提问作者Nikhil Bk B K
相关产品推荐
相关产品推荐

