Neo4j Cypher: Filtering a query results based on another query

Viewed 822

I am trying to find a list of names that unique to one query and exclude the ones that are common between the results of two queries. For example, I want the name of the classes that have been taken by students A, B, and C. And exclude from this list the classes that were taken by students D and E. With the help of the answer to this question (Neo4j Cypher: exclude certain nodes from result), I tried this Cypher code and it works, but I get the results as nodes. I want it as a list of names, not nodes.

Match (m:class)-[r]-(n:student) where n.name in ['aa','bb','cc']    
WITH COLLECT(m) AS EXCLUDED
MATCH  (m1:class)-[r1]-(n1:student) where n1.name in ['dd','ee'] 
WITH EXCLUDED, COLLECT(m1) AS included
RETURN FILTER(m1 IN included WHERE NOT m1 IN EXCLUDED)

Thank you!

1 Answers

You can have another WITH and UNWIND.

Match (m:class)-[r]-(n:student) where n.name in ['aa','bb','cc']    
WITH COLLECT(m) AS EXCLUDED
MATCH  (m1:class)-[r1]-(n1:student) where n1.name in ['dd','ee'] 
WITH EXCLUDED, COLLECT(m1) AS included
WITH FILTER(m1 IN included WHERE NOT m1 IN EXCLUDED) as _results
UNWIND _results as results
RETURN results.name

Note: FILTER() is deprecated in neo4j 3.5 and removed in 4.0 in favor of List Comprehension

Related