David
David

Reputation: 583

How to find the count of distinct nodes between a single node of particular label to all other nodes in a different label in neo4j?

I have 4 different types of labels and multiple nodes in each. Let's say Node A of label P is connected to multiple nodes of label Q and those nodes are connected to multiple nodes of label R. Now I'm trying to figure out the count of distinct nodes in label R that is connected to Node A either directly or through label Q.

Upvotes: 0

Views: 79

Answers (1)

cybersam
cybersam

Reputation: 66999

This should work:

MATCH path = (a:P)-[*1..2]->(r:R)
WHERE a.id = 'A' AND (LENGTH(path) = 1 OR 'Q' IN LABELS(NODES(path)[1]))
RETURN DISTINCT r

This simple example assumes a consistent "forward" relationship directionality for both relationships.

[ADDENDUM]

This should be a better query than that one asked about in the comments:

MATCH path = allShortestPaths((a:P)-[*1..2]->(r:R))
WHERE a.id = $resource_key AND (LENGTH(path) = 1 OR 'Q' IN LABELS(NODES(path)[1]))
RETURN COUNT(DISTINCT r)

Upvotes: 1

Related Questions