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

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

我有一个如下所示的节点层次结构,其中节点 c1..c6 的类型为:Category,它们的子节点 i1..i7 的类型为:Item。

我需要获取的是每个Category中的Item数量,包括它们的子分类。输出应如下所示:

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

目前我有一个查询 returns 子节点的正确数量,但是项目的数量只显示每个节点,而不是总计。不确定我是否遗漏了任何东西,或者这是否不是正确的方法?

重要的是要注意,我不能依赖于自己指定起始节点,因为它会随着时间在数据库中发生变化,因此查询应该从没有父节点的类别节点开始。

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

现在的输出:

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

对于未来的访问者,这是我从 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

有关详细信息,请参见此处:

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