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

Python创建RedisGraph节点出现AttributeError的原因及修正方案

解决RedisGraph AttributeError: 'str' object has no attribute 'execute_command' 错误

问题重现

你运行了以下Python代码尝试创建RedisGraph节点:

import redis
from redisgraph import Node, Edge, Graph

r = redis.Redis(host='localhost', port=6379)
g = Graph('graph', 'r')  # 问题出在这里
test3 = Node(label='test3', properties={ 'abc' : 9, 'age': 33})
g.add_node(test3)
g.commit()

触发了如下错误堆栈:

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-b6b3d9b0a206> in <module>()
----> 1 g.commit()
/usr/local/lib/python2.7/dist-packages/redisgraph/client.pyc in commit(self)
134 query = query[:-1]
135
--> 136 return self.query(query)
137
138 def flush(self):
/usr/local/lib/python2.7/dist-packages/redisgraph/client.pyc in query(self, q)
153 statistics = None
154 result_set = None
--> 155 response = self.redis_con.execute_command("GRAPH.QUERY", self.name, q)
156
157 result_set = response[0]
AttributeError: 'str' object has no attribute 'execute_command'

错误原因

问题出在创建Graph实例的这一行:

g = Graph('graph', 'r')

你把*字符串'r'*传给了Graph构造函数的第二个参数,但实际上这个参数需要的是一个已经初始化好的Redis客户端实例(也就是你之前创建的r变量)。当Graph内部尝试调用这个“连接对象”的execute_command方法时,发现它只是个字符串,自然没有这个方法,于是抛出了AttributeError。

解决方法

只需要把创建Graph实例的代码修改为:

g = Graph('graph', r)

这里的r是你之前通过redis.Redis()初始化的Redis客户端实例,而非字符串'r'。修改后重新执行代码,就能正常将节点提交到RedisGraph中了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:51:55