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.

Cypher: Match nodes that share the exact same relationships

Hi,

I'm stuck on the following problem...

I have a simple graph with Person and Product nodes, and BOUGHT relationships.

I need a cypher query that will return pairs (or lists) of Person nodes that bought exactly the same products.

So for instance, on the left below, Person A and Person B satisfy the condition, whereas in the example on the right they do not (because Person B hasn't bought Product 1. 

benjamintre_0-1672915826470.png

I hope this makes sense, I don't really have any idea where to start so any pointers will be greatly appreciated!

Thanks

1 ACCEPTED SOLUTION

If the a pair of persons purchased exactly the same products, that means the number of products they purchased the same must equal the number of products each of them purchased individually. The query below derives pairs of people using this approach:

match(p1:Person)-[:BOUGHT]->(:Product)<-[:BOUGHT]-(p2:Person) 
where id(p1)<id(p2)
with p1, p2, count(*) as numOfProducts
where size((p1)-[:BOUGHT]->(:Product)) = numOfProducts 
and size((p2)-[:BOUGHT]->(:Product)) = numOfProducts
return p1.name as name1, p2.name as name2

 Screen Shot 2023-01-05 at 9.52.38 AM.png

Screen Shot 2023-01-05 at 9.52.18 AM.png

View solution in original post

2 REPLIES 2

If the a pair of persons purchased exactly the same products, that means the number of products they purchased the same must equal the number of products each of them purchased individually. The query below derives pairs of people using this approach:

match(p1:Person)-[:BOUGHT]->(:Product)<-[:BOUGHT]-(p2:Person) 
where id(p1)<id(p2)
with p1, p2, count(*) as numOfProducts
where size((p1)-[:BOUGHT]->(:Product)) = numOfProducts 
and size((p2)-[:BOUGHT]->(:Product)) = numOfProducts
return p1.name as name1, p2.name as name2

 Screen Shot 2023-01-05 at 9.52.38 AM.png

Screen Shot 2023-01-05 at 9.52.18 AM.png

wonderful answer, thank you @glilienfield !