Unexpected result using queries with optional relationships

15 views
Skip to first unread message

matias...@brinqa.com

unread,
Feb 1, 2016, 6:10:29 PM2/1/16
to Neo4j
Hi all,

I'm having a hard time building a query with optional relationship using Neo4j 2.3.2.

My query is something like this:

MATCH 
    (n1:Label1)
WHERE 
    (n1.propertyA = {param1})
OPTIONAL MATCH 
    (n1)<-[r:rel1]-(n2:Label2)
WHERE
    (NOT (n1)<-[r:rel1]-(n2) OR n2.propertyB = {param2})
RETURN
    n1;

My intention is to return all n1 objets that don't have a relationship to n2 or if they have a relationship check for propertyB and filter by that. 
What I'm getting is all the n1 even when rel1 exists and propertyB != {param2}

Anyone sees what's the issue in this query? I can't see it...

Thanks,
Matias.
 


matias...@brinqa.com

unread,
Feb 1, 2016, 6:27:10 PM2/1/16
to Neo4j
One more thing to add is that what I was doing for previous versions of Neo4j and it was working (but it's not allowed anymore) is the following:

START
   n1=({node})
MATCH
   n1<-[r?:rel1]-n2
WHERE 
   n1.propertyA = {param1} AND (r is null OR n2.propertyB! = {param2})
RETURN 
  n1;

Thanks,
Matias.

Max De Marzi Jr.

unread,
Feb 2, 2016, 5:49:56 PM2/2/16
to Neo4j
The  WHERE gets tied to the OPTIONAL MATCH.
If you want the WHERE to apply to the whole thing you need to end the OPTIONAL with a WITH. 
Something like:


MATCH 
    (n1:Label1)
WHERE 
    (n1.propertyA = {param1})
OPTIONAL MATCH 
    (n1)<-[r:rel1]-(n2:Label2)
WITH n1, r, n2
WHERE
    (r IS NULL OR n2.propertyB = {param2})
RETURN
    n1;
Reply all
Reply to author
Forward
0 new messages