You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

redis-py调用JSON.SET等命令报unknown command错误,求解决

问题原因

redis-py 5.0.7的基础Redis客户端仅支持Redis核心命令,不包含ReJSON、RedisSearch这类扩展模块的命令。虽然你的Redis Stack镜像已经启用了这些模块,但基础客户端无法识别并发送这类扩展命令,因此会抛出unknown command错误。

解决方法

方法一:使用redis-py的扩展客户端(推荐)

redis-py官方针对Redis Stack的扩展命令提供了专门的封装,直接通过对应子模块调用即可:

  1. 确保redis-py版本正常(5.0.7本身支持,若有问题可升级:pip install --upgrade redis)
  2. 代码中通过整合了扩展能力的Redis客户端,调用对应子模块执行命令:
from redis import Redis
from redis.commands.json.path import Path
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.field import TextField, NumericField

# 初始化Redis连接
r = Redis(host='localhost', port=6379, db=0)

# 执行JSON.SET
r.json().set('user:1', Path.root_path(), {"name": "Alice", "age": 28})

# 执行JSON.GET
user_data = r.json().get('user:1')
print(user_data)

# 执行FT.CREATE创建JSON索引
schema = (
    TextField("$.name", as_name="username"),
    NumericField("$.age", as_name="user_age")
)
index_def = IndexDefinition(prefix=['user:'], index_type=IndexType.JSON)
r.ft('user_idx').create_index(schema, definition=index_def)

方法二:直接用execute_command发送命令

如果不想调整客户端结构,也可以手动调用execute_command方法直接传入原始Redis命令:

from redis import Redis

r = Redis(host='localhost', port=6379, db=0)

# 执行JSON.SET
r.execute_command('JSON.SET', 'user:2', '$', '{"name": "Bob", "age": 32}')

# 执行JSON.GET
user_data = r.execute_command('JSON.GET', 'user:2')
print(user_data)

# 执行FT.CREATE
r.execute_command('FT.CREATE', 'user_idx2', 'ON', 'JSON', 'PREFIX', '1', 'user:', 'SCHEMA', '$.name', 'AS', 'username', 'TEXT', '$.age', 'AS', 'user_age', 'NUMERIC')
验证要点
  • 确认Redis Stack容器正常运行,CLI能正常执行JSON.SET、FT.CREATE等命令
  • 运行修改后的代码,检查是否能正常返回结果
  • 若仍有问题,可重启Redis容器或重新安装redis-py确保依赖正确

内容的提问来源于stack exchange,提问作者Georgy K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 23:22:05