Tinkerpop 3:使用Gremlin遍历计算连通组件

时间:2015-11-24 13:58:53

标签: gremlin connected-components tinkerpop3

我认为标签很好地解释了我的问题:)

我一直在尝试编写一个Gremlin遍历来计算帖子末尾描述的简单图形的连通分量。

我试过

g.V().repeat(both('e')).until(cyclicPath()).dedup().tree().by('name').next()

获得

==>a={b={a={}, c={b={}}, d={c={d={}}}}, c={d={c={}}}}
==>e={f={e={}, g={f={}}}, h={f={h={}}}}
==>g={f={g={}}}

这很糟糕,因为cyclicPath过滤器在到达e之前终止了从g开始的遍历。 显然,如果我删除until子句,我会得到一个无限循环。 此外,如果我使用simplePath,则遍历在一步之后结束。 有没有办法告诉它以深度优先的顺序探索节点?

干杯!

a = graph.addVertex(T.id, 1, "name", "a")
b = graph.addVertex(T.id, 2, "name", "b")
c = graph.addVertex(T.id, 3, "name", "c")
d = graph.addVertex(T.id, 4, "name", "d")
e = graph.addVertex(T.id, 5, "name", "e")
f = graph.addVertex(T.id, 6, "name", "f")
g = graph.addVertex(T.id, 7, "name", "g")
h = graph.addVertex(T.id, 8, "name", "h")

a.addEdge("e", b)
a.addEdge("e", c)
b.addEdge("e", c)
b.addEdge("e", d)
c.addEdge("e", d)

e.addEdge("e", f)
e.addEdge("e", h)
f.addEdge("e", h)
f.addEdge("e", g)

2 个答案:

答案 0 :(得分:2)

此查询was also discussed in the Gremlin-users group。 这是我提出的解决方案。 @Daniel Kuppitz也有一个有趣的解决方案,你可以在上面提到的帖子中找到。

我认为如果在无向图中总是如此,则连接组件遍历的“最后”节点会导致先前访问过的节点(cyclicPath())或者具有度<0的此节点查询应该工作

g.V().repeat(both('e')).until( cyclicPath().or().both('e').count().is(lte(1)) ).dedup().tree().by('name').next()

在我的例子中,它提供了以下输出

gremlin>  g.V().repeat(both('e')).until(cyclicPath().or().both('e').count().is(lte(1))).dedup().tree().by('name').next()
==>a={b={a={}, c={b={}}, d={c={d={}}}}, c={d={c={}}}}
==>e={f={e={}, g={}, h={f={}}}, h={f={h={}}}}

答案 1 :(得分:1)

仅是为了增强@Alberto版本,该版本运行良好即可,您可以使用simplePath()遍历步骤(http://tinkerpop.apache.org/docs/current/reference/#simplepath-step)来确保遍历器不会在图形中重复其路径

g.V().repeat(both().simplePath())
  .until(bothE().count().is(lte(1)))
  .dedup().tree().by('name').next()