简体   繁体   English

Cypher Neo4j在两个节点之间创建关系并避免双向关系

[英]Cypher Neo4j creating Relationship between two nodes and avoiding bidirectional relationship

Here is my query: 这是我的查询:

   MATCH (a:Person)-[:friend]->(p:Person)<-[:friend]-(b:Person)
   WITH a, b, COUNT(p) as count
   WHERE count >= 2
   CREATE (a)-[:friend {new: "yes"}]->(b)
   RETURN a,b,count

I tried to find a and b that have at least 2 common friends and creating friend relationship between them. 我试图找到具有至少2个共同朋友的a和b,并在它们之间建立朋友关系。 Here is the result sample: 这是结果示例:

   a             b            count
   name1         name2          3
   name2         name1          3

Notes that the result is repeated, and this will create a bi-directional relationship between them. 注意结果是重复的,这将在它们之间创建双向关系。 name1-[:friend]->name2 also means name1<-[:friend]-name2, so if I created a bi-directional relationship, the relationship between them will be duplicated as shown in my csv file: name1-[:friend]-> name2也表示name1 <-[:friend] -name2,因此,如果我创建了双向关系,它们之间的关系将被复制,如我的csv文件所示:

   a             b            relationship
   name1         name2           friend
   name1         name2           friend
   name2         name2           friend
   name2         name2           friend

Is there any way I can avoid this? 有什么办法可以避免这种情况吗? Thank you for your time. 感谢您的时间。

Yeah, there's a trick to do this: 是的,有一个技巧可以做到这一点:

MATCH (a:Person)-[:friend]->(p:Person)<-[:friend]-(b:Person)
WHERE ID(a) < ID(b)
WITH a, b, COUNT(p) as count
WHERE count >= 2
CREATE (a)-[:friend {new: "yes"}]->(b)
RETURN a,b,count

The change is the WHERE ID(a) < ID(b) which makes sure that just one of the two directions is chosen 所做的更改是WHERE ID(a) < ID(b) ,这可以确保仅选择两个方向之一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM