nemo
nemo

Reputation: 311

Gremlin: Retrieve Path which includes edges with match

I'm learning Gremlin-Tinkerpop and trying to make a query to retrieve Paths with queries using match clauses.

Graph Sample :

A : LabelA ----edge["rel1"]-- B1 : LabelB { prop1 : "val1" }
            |--edge["rel2"]-- B2 : LabelB { prop1 : "val1" }
            |--edge["rel3"]-- B3 : LabelB { prop1 : "val1" }
            |--edge["rel4"]-- B4 : LabelB { prop1 : "val2" }
            |--edge["rel5"]-- B5 : LabelB { prop1 : "val2" }
 

It is easy to retrieve paths including edges. like this

g.V().hasLabel("LabelA").outE().inV().hasLabel("LabelB").path()

But.. with MATCH, I can't retrieve 'edge'

g.V().match(__.as("lba").hasLabel("LabelA").outE().inV().hasLabel("LabelB").as("b")).path()

How can I retrieve paths including edges with MATCH? (without 'as')

g.V().match(__.as("lba").hasLabel("LabelA").outE().as("r1").inV().hasLabel("LabelB").as("b")).path()

Thank you.

Upvotes: 1

Views: 682

Answers (1)

Kelvin Lawrence
Kelvin Lawrence

Reputation: 14371

In general I would not use a match step for this type of query but here are some examples. If you want the edge to appear in a path just use an as step to give it a label. I used the air-routes data set to generate these examples.

gremlin> g.V().match(__.as("lba").hasLabel("airport").outE().inV().hasLabel("airport").as("b")).path().limit(1)
==>[v[1],v[1],v[135],[b:v[135],lba:v[1]]]

gremlin> g.V().match(__.as("lba").hasLabel("airport").outE().as('e').inV().hasLabel("airport").as("b")).path().limit(
1)
==>[v[1],v[1],e[5120][1-route->135],v[135],[b:v[135],lba:v[1]]]    

In cases like this one however, the match step is redundant and actually yields more in the path than you probably want. The better Gremlin way to do this is:

gremlin> g.V().hasLabel("airport").outE().inV().hasLabel("airport").path().limit(1)
==>[v[1],e[5120][1-route->135],v[135]] 

  

Match can be handy in cases like this one (below) but even then you can also express this just using where steps (this finds routes that do not also have a return route back to the starting airport).

gremlin> g.V().hasLabel('airport').
......1>       match(__.as('a').out().as('b'),
......2>             __.not(__.as('b').out().as('a'))).
......3>       select('a','b').
......4>         by('code').
......5>       limit(1)
  
==>[a:JFK,b:LCY]    

This can also be done without using a match step

gremlin> g.V().hasLabel('airport').as('a').
......1>       out().as('b').
......2>       where(__.not(out().as('a'))).
......3>       select('a','b').
......4>         by('code').
......5>         limit(1)    

==>[a:JFK,b:LCY]  

In general, when using match it is likely to be more useful to use select than it is going to be to use path as for complex match situations with many conditions, the path will be long and full of stuff you probably are not interested in.

Upvotes: 2

Related Questions