Reputation: 69
I am trying to execute the following cypher query to create a relationship between all the nodes which are present in the collection nodelist.
START n=node(*)
MATCH(n)
WHERE has(n.Gender)
WITH n.Gender as Gender
WITH collect(n) as nodelist
FOREACH (i in RANGE(0,length(nodelist-2))|
FOREACH(si in [nodelist[i]|
FOREACH(si2 in[nodelist[i+1] |
CREATE UNIQUE (si-[:KNOWS]->si2))))
It gives me an error in the second FOREACH loop at nodelist[i] .
I tried putting nodelist(i) and it gives me an error saying `-' expected but '|' found
Any idea where I am going wrong?
Upvotes: 1
Views: 940
Reputation: 19373
If you want to create a knows relation between all nodes in a collection:
MATCH(n)
WHERE has(n.Gender)
WITH collect(n) as nodelist
FOREACH (x IN nodelist |
FOREACH (y IN filter(z IN nodelist WHERE NOT (z=x)) |
MERGE (x)-[:knows]-(y)
)
)
Note the direction of your relations. Each node will be connected to each other node in nodelist once in a particular direction. If you want double relations i.e. a-[knows]->b as well as b-[:knows]->a you'll have to modify the query accordingly.
Upvotes: 2
Reputation: 2583
Your first FOREACH should be like below. Also I think line 4 is redundant in your query. In case you want to collect gender you can directly do collect(n.Gender) as Gender. Incase you do need to use that line you need to pass n
in the first WITH
too, otherwise it wont be reconginized at the second WITH
clause. Also you dont need to start with START n=node(*)
Try below
MATCH(n)
WHERE has(n.Gender)
WITH collect(n) as nodelist,collect(n.Gender) as Gender
FOREACH (i in RANGE(0,length(nodelist)-2)|
FOREACH(si in [nodelist[i]]|
FOREACH(si2 in [nodelist[i+1]] |
CREATE UNIQUE (si)-[:KNOWS]->(si2) )))
Upvotes: 1