Reputation: 47
If I should have an array, and I want to MERGE
all the element in the array into a path of nodes so that when given the relationship name, the nodes will be created if they do not already exist and then joined underneath each other in which the last element in the array will be the leaf node. How do I write this in CYPHER?
Upvotes: 0
Views: 60
Reputation: 30407
Tomaž's answer is correct, and the way to do this with Cypher alone.
As a supplement to this, if you have APOC Procedures installed, you can use a procedure to perform this linking for you.
Using Tomaž's query with slight modification:
WITH [1,2,3,4,5] as start
UNWIND start as a
MERGE (l:Label{id:a})
WITH collect(l) as array
CALL apoc.nodes.link(array, 'NEXT')
RETURN true // since we can't end the query on a procedure call
Upvotes: 1
Reputation: 6534
I am not entirely sure if I understand you correctly, but if you want to transform an array of elements into a sequential path of nodes use the following query:
WITH [1,2,3,4,5] as start
UNWIND start as a
MERGE (l:Label{id:a})
WITH collect(l) as array
FOREACH(i in RANGE(0, length(array)-2) |
FOREACH(element1 in [array[i]] |
FOREACH(element2 in [array[i+1]] |
MERGE (element1)-[:NEXT]->(element2))))
Upvotes: 1