jobbietronic
jobbietronic

Reputation: 65

Cypher to query when a relationship doesn't exist

I have a pattern like so. A person can make visits (v:Visit {type:'introduction'}) to a property, visits can have different types, such as inventory check, inspection....

Visits have a chronology which is described by a (v:Visit)-[r:NEXT]->(vn:Visit)relationship. At a visit the person may recommend that another visit is scheduled (it may or may not be booked) (v:Visit)-[r:RECOMMEDED]->(i:Inspection)

My question is, is it possible to shape a Cypher query to find visit nodes which have a [r:RECOMMEDED]->(i:Inspection) pattern which DON'T have a Visit of {type: 'inspection'} within 2 [:NEXT] hops?

I have this but I have the issue that it return a collection of relationships.

MATCH (v:Visit)-[r:RECOMMENDED]->(i:Inspection)
WITH v
MATCH (v)-[n:NEXT*1..2]->(vis:Visit)
WHERE NOT((v)-[n]->(vis:Visit {type:'Inspection'}))
RETURN v
LIMIT 10

Upvotes: 2

Views: 1419

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18022

You might want to try OPTIONAL MATCH where you insist that what you want is null, like this:

MATCH (v:Visit)-[r:RECOMMENDED]->(i:Inspection)
OPTIONAL MATCH (v)-[n:NEXT*1..2]->(vis:Visit)
WHERE vis is null
RETURN v
LIMIT 10

An OPTIONAL MATCH lets you look for a pattern that may or may not be there. The WHERE vis is null insists that it not be there. So that's your proof that those Visit items don't have other downstream Visit nodes.

Upvotes: 4

Related Questions