Neo4J how to count all the descendants of a single ancestor for a specified relationship type

755 Views Asked by At

Does Neo4j provide a native query method to search and count all the descendants of a node for a specified relationship type such as REFERRED? I'm trying to build a system to record 'A referred B' type of relationships for each referral. It's required to real time count all the references from A down to the bottom which was caused by A. The picture might look like this:

        A
       / \
      B   C
     / \  /\
    D  E F  G
   / \  / \  \ 
  M   N O  P  Q

ANY suggestion please?

Thanks!

1

There are 1 best solutions below

2
Evan Jones On

You can use the the Cypher query language to investigate Neo4j graphs; and certainly with Cypher you can construct a query to give you the answer to your question.

Assuming for your question the A node has an id property of uid='A'and the relationship type is 'Referred' then the query could look like:

MATCH ({uid:'A'}) -[:Referred *1..]-> (n) RETURN COUNT(DISTINCT n)

Here the first part

MATCH ({uid:'A'}) 

indicates a starting point for your query. The Second part

-[:Referred *1..]->

describes which relations to follow. The next part

(n)

names the terminating nodes for your query and lastly

RETURN COUNT(DISTINCT n)

returns a count of those nodes.