在Neo4J数据库中查找叶节点

8
我们有一个项目使用Spring Data Neo4J。其中一个重要实体如下所示:
@NodeEntity
public class Category {
    @GraphId
    Long id;

    String name;

    @RelatedTo(direction = Direction.INCOMING, type = "CHILD")
    Category parent;

    @RelatedTo(direction = Direction.OUTGOING, type = "CHILD")
    Set<Category> children;
}

我们需要找到所有叶子类别(即没有任何子类别的类别)的要求,从一个已知名称的特定类别开始。例如,给定以下层次结构:
Electronics
    Camera
        Point and Shoot
        SLR
    Computing
        Desktop
        Laptop
        Tablet
        Netbook
Furniture
    Tables
        Office tables
        Home tables
    Chairs
        Lounge chairs
        Office chairs

搜索"Furniture"应该返回"办公桌"、"家庭桌子"、"休息椅"和"办公椅"。同样,搜索"Computing"应该返回"台式机"、"笔记本电脑"、"平板电脑"和"上网本"。
需要帮助创建一个密码查询,可以放置在Spring Data存储库方法中,以便从指定节点开始给我所有叶节点。
编辑后的以下查询(与相关的Spring Data存储库方法)在Wes的帮助下工作:
@Query(
"START  category=node:__types__(className='org.example.domain.Category') " +
"MATCH  category-[:CHILD*0..]->child " +
"WHERE  category.name={0} AND NOT(child-[:CHILD]->()) " +
"RETURN child")
List<Category> findLeaves(String name);
2个回答

18

这是我用cypher找到的最简单的方法:http://console.neo4j.org/r/cgrndo

start n=node(*) // you can specify a single node here if you want
match n-[r*]->m
where not(m-->()) // this limits m to be only leaf nodes 
return distinct m; // this returns the distinct leaf nodes (not necessary if there are only simple paths)

编辑:(由于最近有人给这篇文章点赞...这里更新使用3.x的cypher)

match (n) 
where not (n)-->() 
return distinct n

-1
如果您想在Cypher 3.0中查找所有的叶节点,请访问以下链接:
http://console.neo4j.org/r/leaf-nodes 使用以下代码:match (n)-[r]-() with n, count(r) as c where c = 1 return n

只有在图的父/子关系中方向不是因素时(其中2个节点子图中的两个节点都被视为叶节点),此方法才有效。否则,此方法将无法正常工作,因为查询还将匹配2个节点子图的父节点(以及其子节点)。按定义,叶节点是没有任何子节点(但至少有一个父节点)的节点,而这并不是此查询正在检查的内容。此查询还将无法识别非树形图中的叶节点,其中存在多个传入关系但没有传出关系。 - InverseFalcon
对于无向图,是的 - Scott

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接