Could I get a count of how many leaves there are connecting each node at each level in Neo4j graph with Cypher?

Viewed 35

It would be helpful if I could get a count of how many leaves there are connecting each node at each level, and save that number as a label.

As an example:

(:Node:Root)->[:ACCESS]->(:Node:a)->[:ACCESS]->(:Node:c)

(:Node:Root)->[:ACCESS]->(:Node:a)->[:ACCESS]->(:Node:e)

(:Node:Root)->[:ACCESS]->(:Node:b)->[:ACCESS]->(:Node:d)

The root node has two nodes connected a,b

a has two nodes connected c,e

b has one node connected d

What I would like to receive is:

The root has 3 leaves connected

Node a has 2 leaves connected

Node b has 1 leaf connected

Node c,d, and e have 0 leaves connected

******* This example has only two levels, but I need it to support an unknown number of levels

Thanks in advance!

1 Answers

You can get the nodes and their leaves count as follows

MATCH (n)
OPTIONAL MATCH (n)-[:ACCESS*]->(leaf) 
WHERE NOT EXISTS((leaf)-[:ACCESS]->())

RETURN n, COUNT(DISTINCT leaf) AS leaves
Related