Asher Yartsev
Asher Yartsev

Reputation: 87

Cypher: filter out nodes with certain paths

Suppose:

  1. I have in my Neo4j database, nodes with SpecialFromLabel in them.
  2. These nodes are connected to SpecialToLabel nodes with SPECIAL_REL relationship
  3. The following paths, therefor, exist: p = (from: SpecialFromLabel)-[r:SPECIAL_REL]->(to: SpecialToLabel)
  4. Nodes with SpecialToLabel have a property to_prop that can have different string values

How can I construct a query that gives me all from nodes that have a path: p=(from: SpecialFromLabel)-[:SPECIAL_REL]->(to: SpecialToLabel) - but those from nodes do not have a path to to nodes, where to.to_prop is in an unwanted values-set?

in pseudocode (not runnable) I want something like this:

MATCH (unwanted_from: SpecialFromLabel)-[r:SPECIAL_REL]->(to: SpecialToLabel)
WHERE (to.`to_prop` in $UnwantedValues)
with unwanted_from
MATCH (from: SpecialFromLabel)-[r:SPECIAL_REL]->(to: SpecialToLabel)
WHERE from not in unwanted_from
RETURN from

Upvotes: 0

Views: 343

Answers (1)

Graphileon
Graphileon

Reputation: 5385

I would approach it like this

// collect the unwanted endpoints
MATCH (to: SpecialToLabel)
WHERE (to.`to_prop` in $UnwantedValues)
WITH COLLECT(to) AS unwantedEndpoints

// only use the 'from' nodes that do not have a relation to one of the unwantedEndpoints
MATCH p=(from: SpecialFromLabel)-[r:SPECIAL_REL]->(to: SpecialToLabel)
WHERE NONE( n IN [(from)-[:SPECIAL_REL]->(m) | m] WHERE n IN unwantedEndpoints)
RETURN p

==== UPDATED , and applied to Movie dataset====

// be careful not to re-use the bindings!
MATCH (persons:Person)-[a:ACTED_IN]->(m:Movie) 
WHERE ((m.title in ["Speed Racer"])) 

with collect(m) as excluded  

MATCH (p:Person)-[:ACTED_IN]->(:Movie)  
WHERE  none(n in [(p)-[:ACTED_IN]->(m2:Movie)| m2] where n in excluded)  

RETURN DISTINCT p.name,[(p)-[:ACTED_IN]->(m3:Movie)| m3.title]
ORDER BY p.name

Upvotes: 1

Related Questions