Tinkerpop 3: compute connected components with Gremlin traversal

元气小坏坏 提交于 2019-12-06 13:39:09

This query was also discussed in the Gremlin-users group. Here is the solution I came out with. @Daniel Kuppitz also had an interesting solution you can find in the mentioned thread.

I think that if it is always true that in an undirected graph the "last" node of the traversal of a connected component either leads to a previously visited node (cyclicPath()) or has degree <=1 this query should work

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

On my example it gives the following output

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={}}}}
Eldinea

Just to enhance the @Alberto version, which is working well, you can use the simplePath() traversal step (http://tinkerpop.apache.org/docs/current/reference/#simplepath-step) to ensure that the traverser does not repeat its path through the graph

g.V().repeat(both().simplePath())
  .until(bothE().count().is(lte(1)))
  .dedup().tree().by('name').next()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!