cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Is there a simple way to make two partial queries?

Hi all. I have an old question that I resolved programmatically (two different queries on the router), but I'd like to know if there is a way to solve it directly in Cypher.

What do I need, is to restrict the results of a query, but only if a param is not null, like in the following sample

MATCH (recipe:Recipe {uuid: '10f204f9-7505-477b-8d29-71124615c10f'})<-[d:CAN_BE_SUGGESTED_FOR]-(mention:Mention)

MATCH (recipe)<-[d:CAN_BE_SUGGESTED_FOR]-(mention)-[:SOLD_BY]->(customer:Customer {name: $parm }) 

// ... other MATCHES AND MERGES related on previous results

RETURN recipe.name,mention.name;

If I run this query, the first match returns n nodes.
If $parm is not null, the second query return a number of nodes <= n.
If $parm is null the second query always returns (of course) 0 nodes and the entire query returns no records

So, the question is: How can I write a query so that it runs the second match only if $parm is not null?

PS: OPTIONAL doesn't sort the required effect.

Any suggestion is appreciated.

1 ACCEPTED SOLUTION

jackson1
Node Link

Can you elaborate why OPTIONAL MATCH doesn't achieve the required effect?

This a good read on the different ways we can write conditional queries.:

e.g.

MATCH (recipe:Recipe {uuid: '10f204f9-7505-477b-8d29-71124615c10f'})<-[d:CAN_BE_SUGGESTED_FOR]-(mention:Mention)
CALL {
  WITH recipe, mention
  WITH recipe, mention 
  WHERE $parm IS NOT NULL
  // more code

  UNION

  WITH recipe, mention
  WITH recipe, mention 
  WHERE $parm IS NULL
  // more code

}

RETURN recipe.name,mention.name;

View solution in original post

1 REPLY 1

jackson1
Node Link

Can you elaborate why OPTIONAL MATCH doesn't achieve the required effect?

This a good read on the different ways we can write conditional queries.:

e.g.

MATCH (recipe:Recipe {uuid: '10f204f9-7505-477b-8d29-71124615c10f'})<-[d:CAN_BE_SUGGESTED_FOR]-(mention:Mention)
CALL {
  WITH recipe, mention
  WITH recipe, mention 
  WHERE $parm IS NOT NULL
  // more code

  UNION

  WITH recipe, mention
  WITH recipe, mention 
  WHERE $parm IS NULL
  // more code

}

RETURN recipe.name,mention.name;