Search code examples
azure-cosmosdbgremlinazure-cosmosdb-gremlinapi

Gremlin DFS/BFS Search while avoiding Loops


In Gremlin I am trying to get find all the connected nodes in my graph - Using either BFS or DFS I am not worried about the traversal method as I will have a list of edges that will show the connections between the nodes where the output would be something like

[
 Nodes : [ {id : 1, name: "abc"}, "{id: 2, name : "pqr"],
 Edges : [ {id : 100, label : ParentOf, from : 1, to : 2 }, {id : 101, label : ChildOf, from : 2, to : 1 }]
]

My Graph Looks something like this

enter image description here

My issues are with cycles - I am trying to emit only the nodes that are connected, say I start with the node 1

g.V('a07771c3-8657-4535-8302-60bcdac5b753').repeat(out('knows')).until(__.not(outE('knows'))).path().
       unfold().dedup().id().fold()

I end up with the error

Gremlin Query Execution Error: Exceeded maximum number of loops on a repeat() step. Cannot exceed 32 loops. Recommend limiting the number of loops using times(n) step or with a loops() condition

I am looking for a way where the query skips the nodes that are already emited? Not exactly sure how to do that


Solution

  • The simplePath step can be used to prevent cycles.

    g.V('a07771c3-8657-4535-8302-60bcdac5b753').
      repeat(out('knows').simplePath()).
      until(__.not(outE('knows'))).path().
      unfold().
      dedup().
      id().
      fold()