Home > Software design >  Neo4j Check a Single Node for multiple Relationships and Return if either exists
Neo4j Check a Single Node for multiple Relationships and Return if either exists

Time:10-19

I am trying to test if any 2 patterns exist on a single Node. IF both patterns are present I get a result BUT if ONLY 1 pattern is present I get no results. HOW do I write the query so that I get a result IF either one or both patterns exist?

enter image description here

(this is an example if BOTH patterns exist - Result is Returned)

MATCH (characteristic)<-[:HAS]-(thing {name:'ball'})<-[:IS_A*]-(decendent)-[r:HAS]->(characteristic)
MATCH (characteristic2)-[r2:HAS]->(thing2 {name:'ball'})<-[:IS_A*]-(decendent2)<-[:HAS]-(characteristic)
RETURN decendent, decendent2

Now imagine if I ONLY have the Bounce Relationship. The Query above will Return Nothing. It only Returns IF Both are True. How do I Match if either is true?

CodePudding user response:

Have a look at OPTIONAL MATCH https://neo4j.com/docs/cypher-manual/current/clauses/optional-match/

Your query can be re-writtten as,

MATCH (characteristic)<-[:HAS]-(thing {name:'ball'})<-[:IS_A*]-(decendent)-[r:HAS]->(characteristic)
OPTIONAL MATCH (characteristic2)-[r2:HAS]->(thing2 {name:'ball'})<-[:IS_A*]-(decendent2)<-[:HAS]-(characteristic)
RETURN decendent, decendent2

This will return results if either descendant is matched by the respective clauses

  • Related