Reputation: 2766
I'm learning Cypher/Neo4j and am playing around with the movie graph dataset. I would like to understand how to write statements that match more complicated subgraphs and return the entire subgraph.
For example, if I want the subgraphs of people who have acted in and directed the same movie, I can use:
MATCH (m:Movie) <-[:DIRECTED]-(p:Person) -[:ACTED_IN]-> (m:Movie)
RETURN *
However, this only works because the subgraph I'm looking for is a straight line. If I wanted to expand the above to match subgraphs of people who both A: directed a movie they acted in and B: acted in a particular movie - "Movie X", I would not know how to do this. I understand I could use a WHERE statement to filter out subgraphs where the actor did not act in "Movie X", but this would not return the node representing "Movie X".
I'm wondering if there's a way to construct such queries - something like the below:
MATCH (p:Person) -[:ACTED_IN]-> (m:Movie) AND
(p:Person) -[:DIRECTED]-> (m:Movie) AND
(p:Person)-[:ACTED_IN]->(:Movie {title: 'Movie X'})
RETURN *
Upvotes: 1
Views: 41
Reputation: 11216
You are absolutely on the right path. Give this a try
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WHERE (p)-[:DIRECTED]->(m)
AND (p)-[:ACTED_IN]->(:Movie {title: 'Movie X'})
RETURN *
In this case since you already know that you want people that acted in Movie X, a better approach in this specific case would be to match 'Movie X' right off the hop such as...
MATCH (p:Person)-[:ACTED_IN]->(m:Movie {title: 'Movie X'})
WHERE (p)-[:DIRECTED]->(m)
RETURN *
In order to return 'Movie X' (although it should be one of the movies already matched you need to identify it in a MATCH
statement. YOu could do something like this...
MATCH (p:Person)-[:ACTED_IN]->(m:Movie)
WHERE (p)-[:DIRECTED]->(m)
WITH p, m
MATCH (p)-[:ACTED_IN]->(m2:Movie {title: 'Movie X'})
RETURN p, m, m2
Upvotes: 1