blu le temps
blu le temps

Reputation: 53

How to return distinct node-pair in Neo4j Cypher?

I have Node type: Person and Neighborhood. When trying to find the persons LIVES in the same neighborhood, I have the persons appeared twice, in different order.

MATCH (p1:Person)-[n1:LIVES]-(n:Neighborhood)-[n2:LIVES]-(p2:Person)  
RETURN n.name, p1.name, p2.name

returns:

"Riverdale", "Paul", "James"
"Riverdale", "Paul", "Mary"
"Riverdale", "James", "Paul"
"Riverdale", "Mary", "Paul"
"Newton", "Zoe", "Harry"
"Newton", "Harry", "Zoe"
...

How can I deduplicate the result set to have the pair appear only once?

"Riverdale", "Paul", "James"
"Riverdale", "Paul", "Mary"
"Newton", "Zoe", "Harry"
...

I tried DISTINCT but it did not work as the list is ordered.

Upvotes: 1

Views: 1345

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

The pattern matches both ways so to eliminate one half of the responses you can add a WHERE clause that specifies the id() of one of the Person nodes is greater than the other.

MATCH (p1:Person)-[n1:LIVES]-(n:Neighborhood)-[n2:LIVES]-(p2:Person)  
WHERE id(p1) > id(p2)
RETURN n.name, p1.name, p2.name

Upvotes: 3

Related Questions