Search code examples
graphnodesgremlintraversaltinkerpop

Gremlin query: How to AND & OR relations?


Say for example I have edges with the types A, B, C or D.

How do I traverse using AND and OR on these edge-types?

Say I want to traverse from node X by ( in(A) AND out(B) ) OR ( both(C) AND out(D) )

The result I expect are all the nodes that have atleast one A-edge that goes to X AND atleast one B-edge that goes from X, OR atleast one C-edge that either goes from or to X AND atleast one D-edge that goes from X.

How do I write a Gremlin query to do this in a general matter? Thank you so much for any help!


Solution

  • I figured it out!

    g.V().union(
    
      // in(A) AND out(B)
      match(
        __.as('1').in('A').as('2'),
        __.as('1').out('B').as('2'))
      .select('2'),
    
      // OR
    
      // both(C) AND out(D)
      match(
        __.as('1').both('C').as('2'),
        __.as('1').out('D').as('2'))
      .select('2'))
    
    // Delete duplicates
    .dedup()