cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

How to get the number of common nodes between 2 nodes?

Hi there, I'm trying to get the number of nodes that are related with 2 specific nodes, so I have wrote the following cypher query:

match (c:Candidate {id: 1})--(n)--(j:Job {id: 2})
return count(n) 

The problem here is that when there is no common nodes between Job and Candidate, the query doesn't return 0.
How can I achieve this behavior?

1 ACCEPTED SOLUTION

clem
Graph Steward

I believe this works:

OPTIONAL match (c:Candidate {id: 1})--(n)--(j:Job {id: 2})
return count(n)

The conceptual hurdle is that OPTIONAL MATCH will return null if nothing matches.
count() of null is 0.

MATCH by itself doesn't return anything, hence count() never gets called.

View solution in original post

6 REPLIES 6

clem
Graph Steward

I believe this works:

OPTIONAL match (c:Candidate {id: 1})--(n)--(j:Job {id: 2})
return count(n)

The conceptual hurdle is that OPTIONAL MATCH will return null if nothing matches.
count() of null is 0.

MATCH by itself doesn't return anything, hence count() never gets called.

It works as expected, thank you.

But now if I want to get the Job and Candidate that has no common nodes I would use something like this:

optional match (j:Job)--(n)--(c:Candidate)
with j,c, count(n) as s
where s = 0
return j.id, c.id

For some reason it does not return the jobs/candidates with no common nodes.

Here, I'm not as knowledgable...

I think you want to try either the exists() function (with NOT) or maybe the existential subquery:

EXISTS { ... }

Let us know how that works out.

MATCH (j:Job),(c:Candidate) WHERE NOT EXISTS { (j)--()--(c) }
RETURN j.id,c.id

WARNING : This query could be heavy time processing

That returns only the Candidate and Jobs that are not related, what if I want to get a list with all the jobs, candidates and how many common nodes they have?

MATCH (j:Job),(c:Candidate)
OPTIONAL MATCH (j)--(n)--(c)
RETURN j.id AS Job, c.id AS Candidate, count(n) AS CommunNodes

Not perfect as I think it will show null instead of 0 in the third column but you can do a find and replace after.