George
George

Reputation: 1582

Finding the path between two vertices in Neo4j using Gremlin

I'm trying to find in a Neo4j database a path in between two vertices, assuming I have code that look like this

newschool = g.addVerttex();
newschool.Title = 'A nice school';

newuser = g.addVertex();
newuser.name = 'student';

g.addEdge(newuser, g.V.filter{it.Title == 'school'}.next(), 'goesto');

I can get back the edge that I wanted if I know the id of both vertices, but of course this is not dynamic:

g.v(2).outE.inV.retain([g.v(1)]).back(2);
==> e[1][2-goesto->1]

so then I tried to change this to be more dynamic expanding on the working query:

g.V.filter{it.name == 'student'}.outE.inV.retain([g.V.filter{it.Title == 'A nice school'}]).back(2);

g.v(g.V.filter{it.name == 'student'}.id).outE.inV.retain([g.v(g.V.filter{it.Title == 'A nice school'}.id)]).back(2)

none of that worked of course...

Why is g.V.filter{it.name =='student'} and g.v(2) different? why is g.V.filter{it.name == 'student'}.id not the same as 2?

What did I miss? How do I get this to work?

Thanks.

Upvotes: 1

Views: 800

Answers (2)

stephen mallette
stephen mallette

Reputation: 46226

Don't think you are iterating your pipeline inside the retain. Note my Gremlin session below using the toy TinkerGraph:

gremlin> g = TinkerGraphFactory.createTinkerGraph()
==>tinkergraph[vertices:6 edges:6]                                     
gremlin> g.v(1).out.retain([g.v(4)])
==>v[4]
gremlin> g.v(1).out.retain([g.V.filter{it.name=='josh'}])
gremlin> g.v(1).out.retain([g.V.filter{it.name=='josh'}.next()])
==>v[4]

Make sure you next() inside the retain:

g.V.filter{it.name == 'student'}.outE.inV.retain([g.V.filter{it.Title == 'A nice school'}.next()]).back(2)

Upvotes: 2

Marko A. Rodriguez
Marko A. Rodriguez

Reputation: 1702

g.v(1).out.loop(1){it.object != g.v(2)}.path

In English:

"Start from vertex 1 and loop over outgoing edges while the object you reach is not vertex 2. Return the path."

See http://gremlindocs.com for more information on such patterns.

Upvotes: 1

Related Questions