S_S
S_S

Reputation: 1402

Gremlin Python shortest path between two nodes

How do we find shortest path between two nodes using gremlin-python?

The example given for gremlin here shows the following gremlin query

g.V(1).repeat(out().simplePath()).until(hasId(5)).path().
       group().by(count(local)).next()

How can I convert this to an equivalent gremlin-python query, given that the source and destination node labels are known?

Upvotes: 1

Views: 485

Answers (1)

Kelvin Lawrence
Kelvin Lawrence

Reputation: 14371

The Gremlin query becomes

g.V().hasLabel(<label1>).
      repeat(out().simplePath()).
      until(hasLabel(<label2>)).
      path().
      group().
        by(count(local)).
      next()

The group...by is not completely needed as the paths returned will be in shortest path order (by depth) i.e. BFS, unless some other weights are used ti find and order them.

In "fully qualified" Gremlin Python (which is not needed if you import the statics etc.) the query becomes:

result = (g.V().hasLabel('label1').
            repeat(__.out().simplePath()).
            until(__.hasLabel('label2')).
            path().
            group().
              by(__.count(Scope.local)).
            next())

Upvotes: 3

Related Questions