Search code examples
gremlintinkerpopjanusgraph

Filter nodes by source Node gremlin


So let's say I have data like so.

(id:1)->(id:2)->(id:3)->(id:4)->(id:5)->(id:6)->(id:9)->(id:10)
(id:5)->(id:7)->(id:8)->(id:6)

To be clear, Id 5 is the same node with 2 edges.

Here is a code sample:

g.addV('person').property('id',1).as('1').
  addV('person').property('id',2).as('2').
  addV('person').property('id',3).as('3').
  addV('person').property('id',4).as('4').
  addV('person').property('id',5).as('5').
  addV('person').property('id',6).as('6').
  addV('person').property('id',7).as('7').
  addV('person').property('id',8).as('8').
  addV('person').property('id',9).as('9').
  addV('person').property('id',10).as('10').
  addE('connection').from('1').to('2').
  addE('connection').from('2').to('3').
  addE('connection').from('3').to('4').
  addE('connection').from('4').to('5').
  addE('connection').from('5').to('6').
  addE('connection').from('6').to('9').
  addE('connection').from('9').to('10').
  addE('connection').from('5').to('7').
  addE('connection').from('7').to('8').
  addE('connection').from('8').to('6').iterate()

I need to traverse the graph, and exclude any node where 6 has a connection, in any direction, to 5. So I would get back:

(id:1)->(id:2)->(id:3)->(id:4)->(id:5)->(id:6)
(id:1)->(id:2)->(id:3)->(id:4)->(id:5)->(id:7)->(id:8)->(id:6)

Solution

  • I'm not sure that I completely understand your question, but it sounds like you want to stop traversing as soon as you see a pattern where you encounter vertex 6 and vertex 6 has an edge to vertex 5 - if so then here's one way to do this:

    gremlin> g.V().has('id',1).
    ......1>   repeat(both().simplePath()).
    ......2>     until(and(has('id',6),
    ......3>               both().has('id',5))).
    ......4>   path().by('id')
    ==>[1,2,3,4,5,6]
    ==>[1,2,3,4,5,7,8,6]
    

    Note that I don't exactly match the output you described in your answer as the traversal starts from vertex 1, so the path taken will include that portion of the path in both cases.