如何在Python中执行Gremlin查询

人气:708 发布:2022-10-16 标签: python gremlin amazon-neptune

问题描述

在Python中,我正在尝试使用Gremlin连接并执行查询。

在这里,我可以使用gremlin连接到海王星数据库,只使用Print语句获取顶点计数:Print(G.V().has(";Sys.tenantID&Quot;,";hLWmgcH61m0bnaI9KpUj6z";).count().next())

但读取文件、存储在变量中并传入gremlin查询不起作用

代码

from __future__  import print_function  # Python 2/3 compatibility

from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

graph = Graph()

remoteConn = DriverRemoteConnection('wss://<URL>:<port>/gremlin','g')
g = graph.traversal().withRemote(remoteConn)

with open ('Orgid1.txt','r') as file:
#    orgstr = file.readlines()
#    orgstr = [orgstr.rstrip() for line in orgstr]
    for line in file:
        print(g.V().has("system.tenantId", line.rstrip()).count().next())

#        print(neptune)




#print(g.V().count())

#print(g.V().has("system.tenantId", "xyz123").count().next())
remoteConn.close()

添加更多详细信息:

这是我使用的代码:

输入:

with open ('Orgid1.txt','r') as file:
    for line in file:
         print(g.V().has("system.tenantId", line.rstrip()).out().count().next())

输出:

$ python3 gremlinexample.py
0

如果我直接打印它,它是有效的。 输入:

print(line.rstrip())

输出:

$ python3 gremlinexample.py
0
xyz123

ps:在名为Orgid1.txt的输入文件中存在xyz123

推荐答案

您需要验证来自文件的文本是否与所需的属性键值完全匹配。我创建了一个简单文件,如下所示:

$ cat values.txt
AUS
LHR
SEA

并将代码的基本结构与航线数据一起使用:

g = graph.traversal().withRemote(connection)
with open ('values.txt','r') as file:
    for line in file:
        print(g.V().has('code', line.rstrip()).out().count().next())

并且运行正常

93
221
122

165