Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
11-10-2021 01:50 AM
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.
Solved! Go to Solution.
11-10-2021 03:13 PM
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;
11-10-2021 03:13 PM
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;
All the sessions of the conference are now available online