Hongli Bu
Hongli Bu

Reputation: 561

How to loop through nodes for a specific label and show how many distinct nodes connect to it (Neo4j)

Hi I am using neo4j as my db. I want to do this thing in neo4j browser: given a label (e.g. Case), find out for every node that belongs to this label, how many distinct node(belongs to the other Label) connect it.

I was trying this:

MATCH (e1:Event) - [hc1:HAS_CASE] -> (c:Case) <- [hc2 :HAS_CASE] - (e2:Event) WHERE e1.eventId <> e2.eventId RETURN c

to list all the c that has two distinct nodes connecting to it.

But every time I ran this, neo4j browser crashed. I am thinking this query might be very memory and time consuming. So what should it do to achieve this?

Upvotes: 0

Views: 194

Answers (1)

cybersam
cybersam

Reputation: 66999

You can use the aggregating function COUNT to find the number of distinct Event nodes that have a HAS_CASE relationship directed at each Case node.

For example:

MATCH (c:Case)
OPTIONAL MATCH (c)<-[:HAS_CASE]-(e:Event)
RETURN c, COUNT(DISTINCT e);

The second MATCH is OPTIONAL so that you will still get a result for Case nodes that have no associated events.

NOTE: The DISTINCT option is only needed if it is possible for a Case node to have multiple HAS_CASE relationships with the same Event node instance.

Upvotes: 1

Related Questions