1
votes

I am trying to write a query in Cypher that returns all leaf nodes given a specific root node.

Right now I have been using:

MATCH (root:Node {name: 'Name'})<-[:REL *]-(leaf:Node)
WHERE NOT (leaf)<-[:REL]-()
RETURN leaf

The problem with this query is that as the database becomes larger, it becomes exponentially slower because every single possible leaf node that connects to my root is checked in the not clause. To omit the not clause, I can return the entire path like this:

MATCH p=(root:Node {name: 'Name'})<-[:REL *]-(leaf:Node) 
RETURN p

The second query is a lot faster as the number of nodes/relationships in the graph increases, but I would prefer to return just the leaf nodes instead of the path.

Is there a way to run this query more efficiently on a larger data set?

1
maybe you could just tail the node list via nodes(p) neo4j.com/docs/cypher-manual/current/functions/list - A. L

1 Answers

0
votes

have you tried this?

MATCH (root:Node {name: 'Name'})<-[:REL *]-(leaf:Node)
WITH leaf
WHERE NOT (leaf)<-[:REL]-()
RETURN leaf

On a similar case for me it gives the lowest number of db hits.