Reputation: 7108
I'm trying to write a query in neo4j
cypher language that creates a relation chain of nodes, sorted by a certain condition.
For example. I have this query:
MATCH (n)
WHERE n.some_property = 'something'
WITH n
ORDER BY n.some_other_property
WITH collect(n) as node_list
I need to link every element of the node_list
with the next element of that list.
Example, if node_list
contains:
[a, b, c, d, e]
The result will be:
CREATE (a)->[:rel]->(b)->[:rel]->(c)->[:rel]->(d)->[:rel]->(e)
So the final query will be:
MATCH (n)
WHERE n.some_property = 'something'
WITH n
ORDER BY n.some_other_property
WITH collect(n) as node_list
CREATE LINKS OF CONSECUTIVE node_list
Is there any way to do it?
Upvotes: 3
Views: 84
Reputation: 7790
Yep! After you have your collection, get a range of indexes with UNWIND:
MATCH (n)
WHERE n.some_property = 'something'
WITH n
ORDER BY n.some_other_property
WITH COLLECT(n) as node_list
UNWIND RANGE(1, SIZE(node_list) - 1) AS idx
WITH node_list[idx - 1] AS from, node_list[idx] AS to
CREATE (from)-[:NEXT]->(to);
Upvotes: 2