Remus 007
Remus 007

Reputation: 102

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

Upvotes: 1

Views: 92

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12704

In case you want to use an APOC function, you can use below. The APOC function will give you a list of all two nodes combination with phone: 123456. Then for each item on the list (UNWIND) is a list of two nodes, n1 and n2. Lastly, create the relationship between n1 and n2.

MATCH (n:platformUser {phone : 123456})
WITH apoc.coll.combinations(collect(n), 2) as nodes
UNWIND nodes as node
WITH node[0] as n1, node[1] as n2
CREATE (n1)-[:test_relation]->(n2)

Upvotes: 1

jose_bacoy
jose_bacoy

Reputation: 12704

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

Upvotes: 1

Related Questions