如何知道在gremlin中从一个顶点遍历到另一个顶点时遇到的顶点数

How to know the number of vertices encountered while traversing from one vertex to another in gremlin

在上图中我们可以看到,我可以从节点1遍历到节点5 2 ,但是从 1 遍历时只遇到一个顶点 3 但对于两个顶点是 54 .

我如何编写一个 gremlin 查询,它将 return 遇到的顶点数。

在询问有关 Gremlin 的问题时,一张图片可能会有所帮助,但提供创建一些示例数据的 Gremlin 脚本更为重要 - 如下所示:

g.addV().property(id,1).as('1').
  addV().property(id,2).as('2').
  addV().property(id,3).as('3').
  addV().property(id,4).as('4').
  addV().property(id,5).as('5').
  addE('link').from('1').to('3').
  addE('link').from('2').to('3').
  addE('link').from('2').to('4').
  addE('link').from('3').to('5').
  addE('link').from('4').to('5').iterate()

在回答你的问题时,我认为你只需要使用 path() 步骤来显示 Gremlin 遍历的位置:

gremlin> g.V().repeat(out()).emit().path()
==>[v[1],v[3]]
==>[v[1],v[3],v[5]]
==>[v[2],v[3]]
==>[v[2],v[4]]
==>[v[2],v[3],v[5]]
==>[v[2],v[4],v[5]]
==>[v[3],v[5]]
==>[v[4],v[5]]

如果您只对顶点 1/2 和 5 之间的路径感兴趣,那么您可以添加一些限制:

gremlin> g.V(1,2).repeat(out()).emit(hasId(5)).path()
==>[v[1],v[3],v[5]]
==>[v[2],v[3],v[5]]
==>[v[2],v[4],v[5]]

在此基础上进一步构建,如果你想计算路径中间的顶点,那么你可以 unfold() 路径,过滤掉你的 start/end 个顶点和 count() :

gremlin> g.V(2).
......1>   repeat(out()).
......2>     emit(hasId(5)).
......3>   path().
......4>   unfold().
......5>   not(hasId(2,5)).
......6>   dedup().
......7>   count()
==>2

希望这能给您一些启发。 Gremlin Recipes.

中有很多很好的例子