使用gremlinpython连接Cosmos DB:同步遍历查询失败求助
问题:gremlinpython连接Azure Cosmos DB时同步遍历查询失效,仅异步查询可用
我尝试用gremlinpython库连接Azure Cosmos DB,发现只有异步查询能正常执行,但同步遍历查询完全无法工作。相关代码如下:
from gremlin_python.driver import client, serializer from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.driver import serializer host = "my_host" username = "my_username" pwd = "COSMOS_KEY" client = client.Client( host, "g", username=username, password=pwd) # 这段代码可以正常运行 callback = client.submit_async("g.V().hasLabel('question')") callback.result().all().result() # 这段代码无法运行 g = traversal().with_remote(client) g.V().hasLabel("question").to_list()
微软官方文档只提供了异步查询的示例,我找不到问题所在。
解决方案
问题核心是同步遍历需要使用DriverRemoteConnection而非直接传入client.Client实例。traversal().with_remote()要求传入RemoteConnection类型对象,底层的Client对象不支持直接绑定遍历器。
修改后的正确代码如下:
from gremlin_python.driver import serializer from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection host = "my_host" username = "my_username" pwd = "COSMOS_KEY" # 初始化DriverRemoteConnection,替代直接使用client.Client remote_conn = DriverRemoteConnection( host, "g", username=username, password=pwd, message_serializer=serializer.GraphSONSerializersV2d0() ) # 异步查询仍可通过remote_conn的client属性执行(可选) callback = remote_conn.client.submit_async("g.V().hasLabel('question')") callback.result().all().result() # 同步遍历现在可以正常工作 g = traversal().with_remote(remote_conn) result = g.V().hasLabel("question").to_list() print(result) # 使用完毕后关闭连接释放资源 remote_conn.close()
关键说明:
DriverRemoteConnection是为Gremlin遍历器设计的远程连接封装,会处理同步遍历的请求序列化和响应解析逻辑,这是client.Client不具备的能力。- 必须指定
message_serializer为GraphSONSerializersV2d0(),Azure Cosmos DB Gremlin API仅兼容GraphSON 2.0格式,默认序列化器不匹配会导致请求失败。 - 同步遍历执行完成后,务必调用
remote_conn.close()释放连接资源。
内容的提问来源于stack exchange,提问作者Marco Repetto
相关产品推荐
相关产品推荐

