petrados
petrados

Reputation: 55

Cypher query to list nodes with same relationship attribute

I'm learning Nosql and I'm using Neo4j Sandbox, here are my queries to create my nodes and relationships between them :

CREATE (n0:Student { nb: '0', name: 'A' })
CREATE (n1:Student { nb: '1', name: 'B' })
CREATE (n2:Student { nb: '2', name: 'C' })
CREATE (n3:Student { nb: '3', name: 'D' })
CREATE (n4:Student { nb: '4', name: 'E' })

CREATE (c1:Course { course_nb: '1', course_name: 'Cryptography' })
CREATE (c2:Course { course_nb: '2', course_name: 'Big Data' })
CREATE (c3:Course { course_nb: '3', course_name: 'Cloud' })

CREATE (n1)-[:Follow]->(c1)
CREATE (n2)-[:Follow]->(c1)
CREATE (n3)-[:Follow]->(c1)
CREATE (n3)-[:Follow]->(c2);

I want to list the students nodes who are related to the same course_nb or course_name attribute

Result should be : 
    ╒------------------╤-------------------- -╕
    |  "Students.name" | "Courses.course_name"|
    -------------------|-----------------------
    "B"                | "Cryptography"
    "C"                | "Cryptography"
    "D"                | "Cryptography"

I've tried this query :

MATCH(n:Course)<-[r:Follow]-(name)
RETURN n

This return all the courses related to Students nodes, I've also tried some queries with WHERE and WITH statement but without success

Basically I want to list the students who follow the same course.

Upvotes: 0

Views: 58

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

You can get all students related to a course, either by applying a course_nb filter in the MATCH clause, like this:

MATCH(n:Course{course_nb: '1'})<-[r:Follow]-(person:Student)
RETURN  person.name, n.course_name

Or, you should group the students by course name, and only select the courses, having more than one student, like this:

MATCH(n:Course)<-[r:Follow]-(person:Student)
WITH n.course_name AS cname, COLLECT(person.name) AS persons WHERE size(persons) > 1
UNWIND persons AS personName
RETURN cname, personName

Upvotes: 1

Related Questions