Search code examples
gremlintinkerpop3

Choose between 2 available edges during traversal


I'm relatively new to Gremlin, and the company I'm with is looking to implement a graph database with some temporary edges within it. Each vertex could have 1 or more edge, and each edge would have a property on it that is essentially isTemporary true/false.

When traversing the graph, if "isTemporary" = true we should follow that edge, otherwise we should follow the edge where "isTemporary" = false.

I.e.,

A-[isTemporary:true, value 1] -> B

A-[isTemporary:false, value 2] -> C

B-[isTemporary: false, value 3] -> D

Running a single gremlin query should return A->B->D in this case.

I've looked through TinkerPop3 documentation, and it seems like "choose" may be what I want to use here, but all the examples seem to return a value, when what I want is a traversal to come back so I can repeatedly act on the traversal.

Any help would be appreciated.


Solution

  • You could be looking for the coalesce step.

    Considering this graph:

    g.addV().as('a').property('name', 'A').
      addV().as('b').property('name', 'B').
      addV().as('c').property('name', 'C').
      addV().as('d').property('name', 'D').
      addE('someLink').from('a').to('b').
        property('isTemporary', true).property('value', 1).
      addE('someLink').from('a').to('c').
        property('isTemporary', false).property('value', 2).
      addE('someLink').from('b').to('d').
        property('isTemporary', false).property('value', 3)
    

    The following query will return all paths from A to D, attempting to traverse via isTemporary: true edges if present, or via isTemporary: false edges otherwise (coalesce step), iteratively.

    g.V().has('name', 'A').
      repeat(
        coalesce(
          outE().has('isTemporary', true).inV(),
          outE().has('isTemporary', false).inV()
        )
      ).
      until(has('name', 'D')).
      path().by('name')
    

    Result:

    ==>[A,B,D]