Traverse from first node to last node using cypher language

Viewed 426

I have created nodes and and relationship. I need to traverse from first node to last node. The output i expect to be displayed as India --> Tamil Nadu --> Chennai --> Kanchipuram --> Vandalur.

Any idea how to display this path?

Below query used to create the nodes and relationships

CREATE (in:place {name:"India", continent:"Asia", Language:"English"}),
    (tn:place {name:"Tamil Nadu", continent:"Asia", Language:"Tamil"}),
    (ap:place {name:"Andra Pradesh", continent:"Asia", Language:"Telugu"}),
    (ch:place {name:"Chennai", continent:"Asia", Language:"Tamil"}),
    (co:place {name:"Coimbatore", continent:"Asia", Language:"Tamil"}),
    (ka:place {name:"Kanchipuram", continent:"Asia", Language:"Tamil"}),
    (th:place {name:"Thiruvallur", continent:"Asia", Language:"Tamil"}),
    (va:place {name:"Vandalur", continent:"Asia", Language:"Tamil"}),
    (pa:place {name:"Padapai", continent:"Asia", Language:"Tamil"}),
(in)- [:parent] ->(tn),
(in)- [:parent] ->(ap),
(tn)- [:parent] ->(ch),
(tn)- [:parent] ->(co),
(ch)- [:parent] ->(ka),
(ch)- [:parent] ->(th),
(ka)- [:parent] ->(va),
(ka)- [:parent] ->(pa)
2 Answers

Neo4j offers the shortest path algorithm, other graph databases may differ (see documentation).

MATCH (start:place { name: "India" }), (end:place { name: "Vandalur" }), p = shortestPath((start)-[:parent*]-(end)) RETURN p ;

If you have a clean tree structure you could also start on the target node and find all incoming parent relationships, which would eventually reach the root node, like this:

MATCH (start:place { name: "Vandalur" })<-[:parent*]-(root:place) 
RETURN start, root;
MATCH (a:place)--(b:place)--(c:place)--(d:place)--(e:place)
RETURN a,b,c,d,e;
Related