Search code examples
graphneo4jcypher

Cypher Statement.SyntaxError Error in looping with foreach and creating relationships


I would like to link nodes pairwise with a common attributes. I use Cypher with neo4j 5.2.

I have the following statement:

MATCH (n:platformUser {phone : 123456})
WITH collect(n) as nodes
FOREACH (i in range(0, size(nodes)-1) |
CREATE (nodes[i])-[:test_relation]->(nodes[i+1]) )

Unfortunately it does not work. I have the following error message.

Invalid input '(': expected "allShortestPaths" or "shortestPath" (line 4, column 12 
(offset: 116))
" CREATE (nodes[i])-[:test_relation]->(nodes[i+1]))"

        ^

I have try a couple things with the brackets or without .My guess is that is a small bug but I don't see what I am missing. Does someone know what is wrong ? Thanks in advance


Solution

  • You can do UNWIND and it will do a cartesian product (combinations) in the collection nodes. On line#5, you need to ensure that n1 is not the same with n2 thus n1<n2

    MATCH (n:platformUser {phone : 123456})
    WITH collect(n) as nodes, size(collect(n)) as sz
    UNWIND nodes[0..sz-1] as n1
    UNWIND nodes[1..sz] as n2
    WITH n1, n2 WHERE n1<n2
    CREATE (n1)-[:test_relation]->(n2) 
    

    Sample result: enter image description here