简体   繁体   English

Cypher 查询每个节点具有的特定类型关系的数量,包括其子节点中的相同类型关系

[英]Cypher query to count the number of relationships of specific type that each node has, including same type relationships in their sub-nodes

I have a node hierarchy like following, where nodes c1..c6 are of type:Category, and their sub-nodes i1..i7 are of type:Item.我有一个如下的节点层次结构,其中节点 c1..c6 的类型为:Category,它们的子节点 i1..i7 的类型为:Item。

在此处输入图像描述

What I need to obtain is the number of Items in each Category, including their sub-categories.我需要获得的是每个类别中的项目数,包括它们的子类别。 The output should look like this: output 应如下所示:

category    childCount  itemCount
   c1           5           7
   c2           2           4
   c3           1           3
   c4           0           2
   c5           0           1
   c6           0           2

Currently I have a query that returns the correct amount of child nodes, but the number of items is only displayed for each node, not summed up in total.目前我有一个返回正确数量的子节点的查询,但是项目的数量只显示每个节点,而不是总计。 Not sure if I'm missing anything here, or if this is not the right approach?不确定我是否在这里遗漏了什么,或者这不是正确的方法?

It's important to note that I can't rely on specifying the starting node myself, as it can change over time inside the db, therefore the query should start with the Category node that does not have a parent.重要的是要注意,我不能依赖自己指定起始节点,因为它会随着时间在数据库中发生变化,因此查询应该从没有父节点的 Category 节点开始。

MATCH p = (c:Category)-[:IS_PARENT_OF *0..]->(c)
WITH c, apoc.text.join("1" + [rel in relationships(p) | rel.index], '.') as path, size((:Category)<-[:IS_PARENT_OF*]-(c)) as childCount, size((:Item)-[:IS_CATEGORIZED_AS]->(c)) as itemCount, c.name AS name
ORDER BY path
RETURN name, childCount, itemCount

Output as it is now: Output 现在是:

category    childCount  itemCount
   c1           5           0
   c2           2           1
   c3           1           1
   c4           0           2
   c5           0           1
   c6           0           2

For future visitors, this is the solution from an answer I got from neo4j online community:对于未来的访客,这是我从 neo4j 在线社区获得的答案的解决方案:

MATCH (category:Category)
OPTIONAL MATCH (category)-[:IS_PARENT_OF*..10]->(c)
OPTIONAL MATCH (category)<-[:IS_CATEGORIZED_AS]-(item1:Item)
OPTIONAL MATCH (c)<-[:IS_CATEGORIZED_AS]-(item2:Item)
RETURN category.name AS category,
   count(DISTINCT(c)) AS childCount,
   count(DISTINCT(item1)) + count(DISTINCT(item2)) AS itemCount

For more details see here:有关更多详细信息,请参见此处:

https://community.neo4j.com/t/cypher-query-to-count-the-number-of-relationships-of-specific-type-that-each-node-has-including-same-type-relationships-in-their-sub-nodes-ask-question/17987 https://community.neo4j.com/t/cypher-query-to-count-the-number-of-relationships-of-specific-type-that-each-node-has-including-same-type-relationships-在他们的子节点中询问问题/17987

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

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