Gremlin Python提交字符串查询报partition属性缺失错误
报错原因
核心错误是gremlin_python.driver.client.Client的初始化参数传错类型:
Client用于提交字符串形式的Gremlin脚本,它的第一个构造参数要求传入字符串格式的Gremlin服务WebSocket连接地址,会自行建立原生WebSocket连接。- 你传入的是
DriverRemoteConnection实例,这个对象是给GLV风格的链式遍历API(也就是你之前直接调用g对象方法的写法)封装的连接对象,不是字符串URL。底层Tornado建立连接时会把传入的参数当URL对象处理,尝试调用字符串专属的partition方法解析地址,自然抛出AttributeError: 'DriverRemoteConnection' object has no attribute 'partition'错误。
修复方案
去掉多余的DriverRemoteConnection初始化逻辑,直接将WebSocket地址字符串传入Client构造函数即可,同时注意提交查询后需要遍历结果对象才能拿到实际返回数据,修正后的可运行代码如下:
from gremlin_python.driver import client # 直接传入WS地址,无需构造DriverRemoteConnection gremlin_conn = client.Client('ws://localhost:8182/gremlin', "g") query = "g.V().groupCount().by(label).unfold().project('label','count').by(keys).by(values)" response = gremlin_conn.submit(query) # 遍历获取结果 for item in response: print(item) # 使用完成后关闭连接 gremlin_conn.close()
额外说明
如果需要给Gremlin脚本传动态参数,不要直接拼接字符串,使用bindings参数传入绑定变量即可,既可以避免Gremlin注入风险,也能提升服务端查询缓存命中率,示例:
query = "g.V().has(label_name, prop_key, prop_value).toList()" bindings = { "label_name": "my-label", "prop_key": "k", "prop_value": "v" } response = gremlin_conn.submit(query, bindings=bindings)
内容的提问来源于stack exchange,提问作者user1187968
相关产品推荐
相关产品推荐

