jason
jason

Reputation: 3962

how to create relationships in loop in neo4j

I am trying to create friend relationship to all the ids in the list but I am getting an error:

Node  already exists with label User and property "id"=[2]
 Neo.ClientError.Schema.ConstraintViolation

Basically these ids already exist and I just want to create friend relationship to multiple ids at once using for-each.How can I achieve this or is there any other way to do the same? I really appreciate any help.

MATCH (u:User {id:"3"})
FOREACH (id in ["2","4","5"] |
  MERGE (u)-[:FRIEND]->(:User {id:id}))

Upvotes: 0

Views: 2075

Answers (2)

Luanne
Luanne

Reputation: 19373

The problem is the usage of MERGE. Merge needs you to bind both ends of the relationship if you don't want either node recreated in the absence of the pattern existing between them. u is bound, but because there is no FRIEND relation from u to the other users, the entire pattern is created from u, with the FRIEND relation and a new User node.

You can't MATCH the user in FOREACH so instead, use

MATCH (u:User {id:"3"})
match (fb:User) 
where fb.id in ["2","4","5"] 
MERGE (u)-[:FRIEND]->(fb)

Upvotes: 3

Christophe Willemsen
Christophe Willemsen

Reputation: 20175

As the users already exist, there is a more simple way :

MATCH (u:User {id:"3"})
MATCH (friends:User) WHERE friends.id IN ["2","4","5"]
MERGE (u)-[:FRIEND]->(friends)

Upvotes: 2

Related Questions