Python查询JanusGraph遇异常:count结果异常、查询顶点触发KeyError
问题:Python连接JanusGraph查询异常,获取顶点时报
KeyError: <DataType.custom: 0> 现象描述
按照JanusGraph官方Python连接文档编写代码后,出现以下异常情况:
- 直接执行
g.V().count()返回遍历步骤而非统计结果:
>>> g.V().count() [['V'], ['count']]
- 调用
to_list()后,统计类查询正常,但获取完整顶点时报错:
>>> g.V().has_label("table").count().to_list() Out[11]: [582] >>> g.V().to_list() Traceback (most recent call last): ...(省略中间栈信息) File "/Users/jianfezhang/github/metadata-repo/metadata-pilot/.venv/lib/python3.11/site-packages/gremlin_python/structure/io/graphbinaryV1.py", line 204, in to_object return self.deserializers[DataType(bt)].objectify(buff, self, nullable) ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ KeyError: <DataType.custom: 0>
复现代码
from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.anonymous_traversal import traversal connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'g') g = traversal().withRemote(connection) # 执行查询 g.V().count()
可能原因
- 版本不兼容:gremlin-python客户端版本与JanusGraph内置的Gremlin Server版本不一致,导致GraphBinary序列化协议不匹配,无法识别服务端返回的自定义数据类型。
- 顶点包含未识别的自定义属性类型:JanusGraph中顶点的属性使用了gremlin-python客户端未注册的自定义类型(如JanusGraph特有的Geoshape、UUID扩展类型等),客户端反序列化时无法处理。
- 序列化配置缺失:默认的GraphBinary序列化器未配置JanusGraph自定义类型的处理逻辑,导致无法解析对应数据。
解决方案
1. 对齐版本
确保gremlin-python版本与JanusGraph自带的Gremlin Server版本完全一致。例如:
- JanusGraph 1.0.0对应gremlin-python 3.6.2
- JanusGraph 0.6.3对应gremlin-python 3.5.3
通过pip安装指定版本:
pip install gremlin-python==3.6.2
2. 避免返回完整顶点
如果不需要完整顶点数据,只查询所需字段,避开无法反序列化的属性:
# 只返回顶点ID和标签 g.V().project('id', 'label').by(T.id).by(T.label).to_list() # 只返回指定属性 g.V().valueMap('name', 'age').to_list()
3. 切换到GraphSON序列化
创建连接时指定使用GraphSON序列化器,替代默认的GraphBinary,避免自定义类型解析问题:
from gremlin_python.driver.serializer import GraphSONSerializersV2d0 connection = DriverRemoteConnection( 'ws://localhost:8182/gremlin', 'g', message_serializer=GraphSONSerializersV2d0() ) g = traversal().withRemote(connection)
4. 注册自定义类型序列化器
如果必须使用GraphBinary且顶点包含JanusGraph特有类型,需要注册对应序列化器(以Geoshape为例):
from gremlin_python.structure.io.graphbinaryV1 import GraphBinaryReader, GraphBinaryWriter from janusgraph_python.structure.io.graphbinary import JanusGraphSONDeserializer, JanusGraphSONSerializer # 自定义序列化器配置 reader = GraphBinaryReader(deserializers=JanusGraphSONDeserializer().deserializers) writer = GraphBinaryWriter(serializers=JanusGraphSONSerializer().serializers) # 创建连接时指定自定义序列化器(需先安装janusgraph-python包) connection = DriverRemoteConnection( 'ws://localhost:8182/gremlin', 'g', message_serializer=GraphBinarySerializersV1(reader, writer) )
内容的提问来源于stack exchange,提问作者zjffdu
相关产品推荐
相关产品推荐

