[英]Retrieve relationships between child nodes using neo4j cypher
I have a following network result when I run this query in neo4j browser:当我在 neo4j 浏览器中运行此查询时,我有以下网络结果:
MATCH (n1:Item {name: 'A'})-[r]-(n2:Item) Return n1,r,n2
At the bottom of the graph, it says: Displaying 6 nodes, 7 relationships
.在图表的底部,它显示: Displaying 6 nodes, 7 relationships
。 But when I look on the table in the neo4j browser, I only have 5 records但是当我在neo4j浏览器中查看表格时,我只有5条记录
n1,r,n2
A,A->B,B
A,A->C,C
A,A->D,D
A,A->E,E
A,A->F,F
So in the java code, when I get the list of records using the code below:因此,在 java 代码中,当我使用以下代码获取记录列表时:
List<Record> records = session.run(query).list();
I only get 5 records, so I only get the 5 relationships.我只得到 5 条记录,所以我只得到 5 条关系。 But I want to get all 7 relationships including the 2 below:但我想获得所有 7 种关系,包括以下 2 种:
B->C
C->F
How can i achieve that using the cypher query?我如何使用 cypher 查询来实现这一点?
There are many ways to achieve this.有很多方法可以实现这一目标。 One ways is to travers to 2nd level and check that the 2nd level node is in the first level as well一种方法是遍历到第二级并检查第二级节点是否也在第一级
MATCH (n1:Item {name: 'A'})-[r]-(n2:Item)
WITH n1,collect(r) AS firstRels,collect(n2) AS firstNodes
OPTIONAL MATCH (n2)-[r2]-(n3:Item)
WHERE n3 IN firstNodes
RETURN n1,firstRels,firstNodes,collect(r2) as secondRels
Or you could do a Cartesian product between the first level nodes and match:或者您可以在第一级节点之间进行笛卡尔积并匹配:
MATCH (n1:Item {name: 'A'})-[r]-(n2:Item)
WITH n1,collect(r) AS firstRels,collect(n2) as firstNodes
UNWIND firstNodes AS x
UNWIND firstNodes AS y
OPTIONAL MATCH (x)-[r2]-(y)
RETURN n1,firstRels,firstNodes,collect(r2) as secondRels
Depending on on cardinality of firstNodes and secondRels and other existing relationships one might be faster than the other.根据 firstNodes 和 secondRels 的基数以及其他现有关系,一个可能比另一个更快。
This should work:这应该有效:
MATCH (n:Item {name: 'A'})-[r1]-(n2:Item)
WITH n, COLLECT(r1) AS rs, COLLECT(n2) as others
UNWIND others AS n2
OPTIONAL MATCH (n2)-[r2]-(x)
WHERE x IN others
RETURN n, others, rs + COLLECT(r2) AS rs
Unlike @FrantišekHartman's first approach, this query uses UNWIND
to bind n2
(which is not specified in the WITH
clause and therefore becomes unbound) to the same n2
nodes found in the MATCH
clause.与@FrantišekHartman 的第一种方法不同,此查询使用UNWIND
将n2
(未在WITH
子句中指定,因此变为未绑定)绑定到MATCH
子句中的相同n2
节点。 This query also combines all the relationships into a single rs
list.此查询还将所有关系组合到一个rs
列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.