Neamesis
Neamesis

Reputation: 744

Neo4j: Select related nodes with specific label if they are at least 2

I'm a beginner with Neo4J. I need help, I have this type of graph (very simplified here):

(person:Person)<-[:relation1]-(i:Item)<-[:relation2]-(job:Job)

I don't know how to return a person who has 2 jobs. I don't have only 2 relations between my beginning node and my ending node, and when I try to count it's too long for Neo4J, and I don't know how to write the WHERE clause...

I would like to write something like this

MATCH (person:Person)<-[*]-(job:Job) 
WITH collect(job) AS jobs 
WHERE jobs > 1
RETURN person

Is it possible ? Can somebody help me ?

Upvotes: 1

Views: 170

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

You are pretty close. You need to aggregate the jobs per person. ANd since you have a collection of jobs and not a count of jobs you need to use size() to compare it to 1.

MATCH (person:Person)<-[*]-(job:Job) 
WITH person, collect(job) AS jobs 
WHERE size(jobs) > 1 
RETURN person

ALternatively, you could also do this...

MATCH (person:Person)<-[*]-(job:Job) 
WITH person, count(job) AS num_jobs 
WHERE num_jobs > 1 
RETURN person

It would be better to scope down your original so it is a little tighter and does not result in any runaway queries.

MATCH (person:Person)<-[:relations1|realtiosn2*2]-(job:Job) 
WITH person, count(job) AS num_jobs 
WHERE num_jobs > 1 
RETURN person

Upvotes: 1

Related Questions