Search code examples
neo4jnodesduplication

Neo4J: Avoid repeating nodes


I have a model with students and the courses that they assisted. All students have a groupNumber.

So when I want to get all the students that assisted to same course but are from a different groupNumber I do this:

MATCH (s1:Student)-[:Assisted]-(c:Course), (s2:Student)-[:Assisted]-(c)
WHERE s1.groupNumber <> s2.groupNumber
RETURN s1, s2

This works, however, this shows me something like this:

Paul | Steve
Steve | Paul
Carl |Steve
Steve | Mark

Is there a simple way to avoid showing repeated students?


Solution

  • You almost have it - just add one more clause:

    MATCH (s1:Student)-[:Assisted]-(c:Course), (s2:Student)-[:Assisted]-(c)
    WHERE s1.groupNumber <> s2.groupNumber AND
    s1.groupNumber < s2.groupNumber
    RETURN s1, s2
    

    It looks as though your results are repeated because the matches are occurring twice; once in one order, the other time in the other order. By saying that one groupNumber has to be less than the other, it ensures that only one ordering is possible; so for example Paul | Steve is possible, but Steve | Paul isn't.