Reputation: 664
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!
Upvotes: 0
Views: 848
Reputation: 14391
Using this simple graph
g.addV('1').as('1').
addV('2').as('2').
addV('3').as('3').
addV('4').as('4').
addV('5').as('5').
addE('B').from('2').to('3').
addE('A').from('3').to('2')
Your initial match
step
gremlin> g.V().
......1> match(
......2> __.as('1').in('A').as('2'),
......3> __.as('1').out('B').as('2')).
......4> select('2').by(label)
==>3
can be reduced to simply
gremlin> g.V().as('1').out('B').filter(out('A').as('1')).label()
==>3
Notice only out
steps are used. The first one takes you to any adjacent vertices. The second, inside the filter, looks to see if there are ways back to where you came from (which from the current vertex point of view is another out
relationship).
You can use the same pattern to replace the other match
. The query can be wrapped in an or
step if you truly want or
behavior or keep using union
if you truly want all results that match your constraints.
Upvotes: 1
Reputation: 664
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()
Upvotes: 0