0
votes

I'm sure this is an easy cypher query, but I'm relatively new to cypher, so apologies ahead of time, but I can't find a previously asked question.

If I have a bunch of nodes connected like this: (:Start)-[:NEXT]->(step1)-[:NEXT]->(step2)-[:NEXT]->(step3)-[:NEXT]->etc.

And I want to return all the nodes in this group, I can write this: match (s:Start)-[:NEXT*]->(steps) return s, steps

But what if I want to order them by their distance from the starting node? Is there a characteristic I an apply order by to or is it more complicated than that?

Thanks

2

2 Answers

1
votes

Nodes of paths are returned in their sequenced order, so you can use the nodes collection as starting point :

MATCH (s:Start)-[rels:NEXT*]->(steps)
UNWIND range(1, size(nodes(p))-1) AS i
RETURN nodes(p)[i] as node, i
ORDER BY i

Example of this query against the console example : http://console.neo4j.org/r/7nzgov

1
votes

You can enforce the ordering by introducing a variable on the collection of :NEXT relationships, and ordering by their size (how many :NEXTs to get to the node).

MATCH (s:Start)-[rels:NEXT*]->(steps)
RETURN s, steps
ORDER BY SIZE(rels)