【问题标题】:Finding leaf nodes in a Neo4J database在 Neo4J 数据库中查找叶节点
【发布时间】:2023-03-19 19:24:01
【问题描述】:

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

【问题讨论】:

    标签: neo4j spring-data spring-data-neo4j


    【解决方案1】:

    这是我用 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 密码的更新)

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

    【讨论】:

      【解决方案2】:

      如果您要查找 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 节点子图的父级(以及它的子级)。根据定义,叶节点是没有任何子节点(但至少有一个父节点)的节点,这不是此查询要检查的内容。此查询也将无法识别非树图中的叶节点,其中有多个传入关系但没有传出关系。
      • 无向图是的
      猜你喜欢
      • 2011-04-22
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多