7

我们有一个使用 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

搜索“家具”应返回“办公桌”、“家用桌”、“休闲椅”和“办公椅”。同样,搜索“计算”应返回“台式机”、“笔记本电脑”、“平板电脑”和“上网本”。

在创建可以放置在 Spring Data 存储库方法上的密码查询方面需要帮助,以便为我提供从指定节点开始的所有叶节点。

编辑在 Wes 的帮助下,以下查询(使用关联的 Spring Data 存储库方法)起作用:

@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);
4

2 回答 2

15

这是我用密码找到的最简单的方法: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 密码的更新)

match (n) 
where not (n)-->() 
return distinct n
于 2012-10-29T06:39:27.317 回答
-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

于 2017-01-06T18:35:54.597 回答