如何解决Python/Gremlin/AWS Neptune:给定一个节点,最终所有祖先
我使用以下代码在 AWS Neptune 中设置图表。如何找到顶点“a”的所有祖先?
边缘:
a -> b
b -> c
c -> d
d -> e
a -> f
a -> g
g -> h
源代码:
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('http://localhost:9999','g')
g = graph.traversal().withRemote(remoteConn)
g.addV('a').property(id,'1').next()
g.addV('b').property(id,'2').next()
g.addV('c').property(id,'3').next()
g.addV('d').property(id,'4').next()
g.addV('e').property(id,'5').next()
g.addV('f').property(id,'6').next()
g.addV('g').property(id,'7').next()
g.addV('h').property(id,'7').next()
g.V('a').addE('parent').to(g.V('b')).next()
g.V('b').addE('parent').to(g.V('c')).next()
g.V('c').addE('parent').to(g.V('d')).next()
g.V('d').addE('parent').to(g.V('e')).next()
g.V('a').addE('parent').to(g.V('f')).next()
g.V('a').addE('parent').to(g.V('g')).next()
g.V('g').addE('parent').to(g.V('h')).next()
remoteConn.close()
解决方法
您可以使用下面的代码创建图形并返回从 a
到所有祖先的路径。我不得不稍微清理一下上面的代码以修复一些错误,但下面的内容应该适合您。
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.process.traversal import T
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
graph = Graph()
remoteConn = DriverRemoteConnection('wss://<your server name here>:8182/gremlin','g')
g = graph.traversal().withRemote(remoteConn)
g.addV('a').property(T.id,'1').next()
g.addV('b').property(T.id,'2').next()
g.addV('c').property(T.id,'3').next()
g.addV('d').property(T.id,'4').next()
g.addV('e').property(T.id,'5').next()
g.addV('f').property(T.id,'6').next()
g.addV('g').property(T.id,'7').next()
g.addV('h').property(T.id,'8').next()
g.V('1').addE('parent').to(__.V('2')).next()
g.V('2').addE('parent').to(__.V('3')).next()
g.V('3').addE('parent').to(__.V('4')).next()
g.V('4').addE('parent').to(__.V('5')).next()
g.V('5').addE('parent').to(__.V('6')).next()
g.V('6').addE('parent').to(__.V('7')).next()
g.V('7').addE('parent').to(__.V('8')).next()
result = g.V().hasLabel('a').repeat(__.out('parent')).until(__.outE('parent').count().is_(0)).path().toList()
remoteConn.close()
print(result)
我也不确定你是不是故意的,但你给每个顶点一个不同的标签。并不是说你不能这样做,但标签的目的是将项目组合在一起,所以通常你会有这样的事情:
g.addV('person').property(id,'1').next()
g.addV('person').property(id,'2').next()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。