2

I'm trying to match all nodes with specific label that has no relationship or have specific relationship. something like this two queries combined:

MATCH (f:Field) 
OPTIONAL MATCH (f)--(t:Type) 
WHERE id(t) = {id} RETURN f
+
MATCH (f:Field) 
WHERE not (f)--(:Type) 
RETURN f

Something like this:

MATCH (f:Field),(t:Type) 
WHERE id(t) = {id} 
AND NOT (f)--(:Type) 
OR (f)--(t)
RETURN f, id(t) 
ORDER BY id(t) 
LIMIT 10

but this never ends to execute with 150k of :Fields

Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
share_m
  • 23
  • 2

2 Answers2

1

something like this two queries combined:

You can simply use a UNION. The UNION docs says:

The UNION clause is used to combine the result of multiple queries.

Try it:

MATCH (f:Field) OPTIONAL MATCH (f)--(t:Type) WHERE id(t) = {id} RETURN f
UNION
MATCH (f:Field) WHERE not (f)--(:Type) RETURN f

Or you can try changing the second Cypher query to:

// First match 't' where t.id = {id}
MATCH (t:Type)
WHERE id(t) = {id}
// After match f when (f)--(t) or not (f)--(:Type)
MATCH (f:Field)
WHERE (f)--(t)
OR
NOT (f)--(:Type) 
// return desired data
RETURN f, id(t) ORDER BY id(t) LIMIT 10
Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
1

Try something like this:

MATCH (f:Field)
OPTIONAL MATCH (f)--(t:Type)
WITH f, t
WHERE t = null OR id(t) = {id} 
RETURN f

By using a WHERE after a WITH instead of after the OPTIONAL MATCH, we allow it to filter the rows we need, instead of filtering on the OPTIONAL MATCH.

InverseFalcon
  • 29,576
  • 4
  • 38
  • 51