如何在neo4j中创建循环关系

时间:2022-10-12 18:03:49

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

我正在尝试创建列表中所有ID的朋友关系,但我收到一个错误:

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.

基本上这些ID已经存在,我只想使用for-each一次创建与多个id的朋友关系。我如何实现这一点,还是有其他方法来做同样的事情?我非常感谢任何帮助。

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

2 个解决方案

#1


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.

问题是MERGE的使用。如果您不希望在没有它们之间存在模式的情况下重新创建任何节点,则合并需要您绑定关系的两端。你是绑定的,但由于你与其他用户之间没有FRIEND关系,整个模式是从u创建的,具有FRIEND关系和一个新的User节点。

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

你不能在FOREACH中匹配用户,所以请使用

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

#2


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)

#1


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.

问题是MERGE的使用。如果您不希望在没有它们之间存在模式的情况下重新创建任何节点,则合并需要您绑定关系的两端。你是绑定的,但由于你与其他用户之间没有FRIEND关系,整个模式是从u创建的,具有FRIEND关系和一个新的User节点。

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

你不能在FOREACH中匹配用户,所以请使用

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

#2


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)