pHM
pHM

Reputation: 315

Check for value of multiple properties only if they exist in Neo4j

I have nodes of type x with some properties. I am trying to form a query that checks if a given set of properties exist in x, and if they do, compare each them with a value and then return the relevant node. The psuedo code would be something like this:-

match(x)
if exist(x.a, x.b)
   then if(x.a==1 and x.b==2)
         return x
else if exist(x.a)
   then if(x.a==1)
         return x
else if exist(x.b)
   then if(x.b==1)
         return x

I have tried :-

MATCH (x) WHERE exists(x.a) and ('high' IN (x.a)) and exists(x.b) and ('high' IN (x.b)) RETURN x

and:-

match(x) where x.a='high' and x.b='high' return x

But the problem with both these queries is that if, say 'a' is not a property in x and 'b' is, it returns null without giving a result based on at least the value of 'b'. I am assuming that is because of the and clause, but I cant find an alternative. I am using neo4j 3.1.3

Upvotes: 1

Views: 1152

Answers (2)

pHM
pHM

Reputation: 315

The UNION operator will help out in this case, making the query something like this:-

match(x) where x.a='high' return x union match(x) where x.b='high' return x

Got the idea from Tom's answer above!

Upvotes: 1

Tom Geudens
Tom Geudens

Reputation: 2656

This might work :

CREATE (:X {a: "first a"})
CREATE (:X {a: "second a", b: "first b"})
CREATE (:X {b: "second b"})

MATCH (x:X)
WHERE exists(x.a)
AND exists (x.b)
AND <any other conditions>
RETURN x
UNION 
MATCH (x:X)
WHERE exists(x.a)
AND NOT exists (x.b)
AND <any other conditions>
RETURN x
UNION 
MATCH (x:X)
WHERE NOT exists(x.a)
AND exists (x.b)
AND <any other conditions>
RETURN x;

Since the three cases return the same thing you can specify the three cases and UNION them together.

Hope this helps, Tom

Upvotes: 0

Related Questions