繁体   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

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

在此处输入图像描述

我需要获得的是每个类别中的项目数,包括它们的子类别。 output 应如下所示:

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

目前我有一个返回正确数量的子节点的查询,但是项目的数量只显示每个节点,而不是总计。 不确定我是否在这里遗漏了什么,或者这不是正确的方法?

重要的是要注意,我不能依赖自己指定起始节点,因为它会随着时间在数据库中发生变化,因此查询应该从没有父节点的 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 现在是:

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-在他们的子节点中询问问题/17987

暂无
暂无

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

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