【问题标题】:How to execute a Gremlin query in Python如何在 Python 中执行 Gremlin 查询
【发布时间】:2021-12-17 14:03:30
【问题描述】:

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

在这里我可以使用 gremlin 连接到 Neptune DB 并仅使用 print 语句获取顶点数:print(gV().has("system.tenantId", "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: xyz123 存在于名为 Orgid1.txt 的输入文件中

【问题讨论】:

  • 当你说不工作时,以什么方式?您收到错误消息还是所有计数都为零或其他?
  • 如果我使用直接命令,例如:print(g.V().has("system.tenantId", "xyz123").count().next())。它工作正常。但是如果使用任何变量来传递它,那么控制台中的输出为“0”
  • 我会首先检查来自文件的值是否与您要查找的属性值完全相同。它可能有额外的空格或类似的东西。

标签: python gremlin amazon-neptune


【解决方案1】:

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

$ 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

【讨论】:

  • 这是我正在使用的代码:输入: ------ 以 open ('/home/ec2-user/ashis/NeptuneCount/Orgid1.txt','r') 作为文件:对于文件中的行: print(gV().has("ystem.tenantId", line.rstrip()).out().count().next()) 输出:------- $ python3 gremlinexample.py 0 如果我直接打印它的工作。输入:------- print(line.rstrip()) 输出:------- $ python3 gremlinexample.py 0 xyz123 ps:xyz123 存在于名为 Orgid1.txt 的输入文件中
  • 嗨,Kelvin,我在描述中添加了更多细节
  • 如果您现在使用out().count(),该顶点实际上是否存在任何边?
  • 我建议你打印len(line),看看行中是否有任何意外字符。只要输入文件正确编码,我粘贴的代码就可以正常工作。
猜你喜欢
  • 2016-05-21
  • 1970-01-01
  • 2020-01-17
  • 2018-04-22
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多