Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding leaf nodes in a Neo4J database

We have a project where we use Spring Data Neo4J. One of the important entities is shown below:

@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;
}

We have a requirement to find out all the leaf categories (that is, categories without any children) starting from a specific category whose name is known. For example, given the hierarchy shown below:

Electronics
    Camera
        Point and Shoot
        SLR
    Computing
        Desktop
        Laptop
        Tablet
        Netbook
Furniture
    Tables
        Office tables
        Home tables
    Chairs
        Lounge chairs
        Office chairs

a search for "Furniture" should return "Office tables", "Home tables", "Lounge chairs" and "Office chairs". Similarly, a search for "Computing" should return "Desktop", "Laptop", "Tablet" and "Netbook".

Need help in creating a cypher query that can be placed on a Spring Data repository method to give me all the leaf nodes starting from the specified node.

EDIT The following query (with the associated Spring Data repository method) worked after help from 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);
like image 466
manish Avatar asked Oct 29 '12 05:10

manish


People also ask

What is node label in Neo4j?

Neo4j recently introduced the concept of labels and their sidekick, schema indexes. Labels are a way of attaching one or more simple types to nodes (and relationships), while schema indexes allow to automatically index labelled nodes by one or more of their properties.

How many nodes can Neo4j store?

Up to 200k nodes and 400k relationships.


1 Answers

This is the simplest way I've found with 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)

Edit: (since people are recently upvoting this... here's an update using 3.x cypher)

match (n) 
where not (n)-->() 
return distinct n
like image 190
Eve Freeman Avatar answered Oct 02 '22 08:10

Eve Freeman