Search code examples
gremlintinkerpop

Gremlin, how to return all vertex pairs that are connected by an edge with a specific label


Take a simple example of airline connection graph as in below picture

enter image description here can we come up with a gremlin query that can return pairs of cities connected by SW? Like [{ATL,CHI},{SFO,CHI},{DAL,CHI},{HSV,DAL}]


Solution

  • Looks like all you probably need is:

    g.V().outE('SW').inV().path()  
    

    If you don't want the edge in the result you can use a flatMap :

    g.V().flatMap(outE('SW').inV()).path()  
    

    To get back some properties rather than just vertices all you need to do is add a by modulator to the path step.

    g.V().flatMap(outE('SW').inV()).path().by(valueMap())
    

    This will return all the properties for every vertex. In a large result set this is not considered a best practice and you should explicitly ask for the properties you care about. There are many ways you can do this using values, project or valueMap. If you had a property called code representing the airport code you might do this.

    g.V().
      flatMap(outE('SW').inV()).
      path().
        by(valueMap('code'))
    

    or just

    g.V().flatMap(outE('SW').inV()).
      path().
        by('code')