chamber5
chamber5

Reputation: 195

How to check if node globally exists and set condition on it in Cypher?

I'm struggling with problem of creating query in Cypher. Let's use this graph as an example:

MERGE(a:Person {name:'Alice', age:38, eyes:'brown'})
MERGE(c:Person {name:'Charlie', age:53, eyes:'green'})
MERGE(d:Person {name:'Daniel', age:54, eyes:'brown'})
MERGE(b:Person {name:'Bob', age:25, eyes:'blue'})
MERGE(a)-[:KNOWS]->(c)
MERGE(a)-[:KNOWS]->(b)
MERGE(c)-[:KNOWS]->(d)
MERGE(b)-[:KNOWS]->(d)

I would like to have query that returns me nodes with name = 'Alice' only if there aren't any nodes with name = 'Bob'. So if there is Bob I would like to see no results.

Here is what I've tried:

1) With exists()

MATCH p =(n)-[*1..3]->(b)
WHERE n.name = 'Alice' AND NOT EXISTS ((n {name: 'Bob'})-[*1..3]->(b))
RETURN p

But it returns all nodes and relationships.

2) With none()

MATCH p =(n)-[*1..3]->(b)
WHERE n.name = 'Alice' AND NONE (x IN nodes(p) WHERE x.name = 'Bob')
RETURN p

This returned all nodes, without Bob...

3) with any()

MATCH p =(n)-[*1..3]->(b)
WHERE n.name = 'Alice' AND NOT ANY (x IN nodes(p) WHERE x.name = 'Bob')
RETURN p

But this gave me the same result as above.

I'm running out of ideas how to return Alice only if Bob is not present. What I would expect from query is to return Alice when I delete Bob, but when such node exists - nothing.

Any help is appreciated:)

Thanks!

Upvotes: 0

Views: 331

Answers (1)

logisima
logisima

Reputation: 7478

You should try this query :

MATCH (n:Person {name:'Alice'})
WHERE NOT (n)-[:KNOWS*..3]-(:Person {name:'Bob'})
RETURN n

Upvotes: 2

Related Questions