Search code examples
gremlintinkerpop3

Gremlin: How to check if adding an edge would result in a cycle


Given a graph, for example:

g.addV().property(id,'a').as('a').
  addV().property(id,'b').as('b').
  addV().property(id,'c').as('c').
  addE('knows').from('a').to('b').
  addE('knows').from('b').to('c').iterate();

How can I detect that adding an edge would result in a cycle? For example, the following operation would introduce a cycle:

g.addE('knows').from('c').to('a').iterate();

I want to know about this cycle without actually adding the edge (so I can prevent cycles).


Solution

  • One idea that comes to mind is to check if a path from 'a' to 'c' already exists and only if it does not, add the edge. Using a coalesce step, the first traversal inside it that returns a result will be honored. So, if a path to V('c') is found then that vertex will be returned. Otherwise the new edge will be created and returned. Hopefully this gives you something to work with even if you end up needing a variation of this approach.

    gremlin>  g.V('a').
    ......1>   coalesce(
    ......2>     repeat(out()).until(hasId('c')),
    ......3>     addE('knows').from(V('c')).to(V('a')))
    ==>v[c]