alexanoid
alexanoid

Reputation: 25790

Neo4j Cypher and query construction based on condition

I have a following Cypher query:

MATCH (d:Decision)<-[:DEFINED_BY]-(ch:Characteristic) 
WHERE d.id = {ownerDecisionId} and ch.lowerName = LOWER({name}) 
OPTIONAL MATCH (ch)-[rcho:CONTAINS]->(cho:CharacteristicOption) 
RETURN ch, rcho, cho

Sometimes I don't need the following part of the query:

OPTIONAL MATCH (ch)-[rcho:CONTAINS]->(cho:CharacteristicOption)

Right now I'm going to introduce a new method with a different query for this purpose but would like to ask - is it a preferred approach in order to achieve this or there is another way in Cypher..for example I can introduce some new boolean variable and based on its value I can add a condition in order to return (or no) the following information: OPTIONAL MATCH (ch)-[rcho:CONTAINS]->(cho:CharacteristicOption)

Upvotes: 2

Views: 203

Answers (2)

cybersam
cybersam

Reputation: 66999

The following query may do what you want without needing to use APOC. It assumes that executeOptionalMatch is a boolean parameter that indicates whether the OPTIONAL MATCH should be executed.

MATCH (d:Decision)<-[:DEFINED_BY]-(ch:Characteristic) 
WHERE d.id = {ownerDecisionId} and ch.lowerName = LOWER({name}) 
OPTIONAL MATCH (ch)-[rcho:CONTAINS]->(cho:CharacteristicOption)
WHERE {executeOptionalMatch}
RETURN ch, rcho, cho

You can get the PROFILE of the query to see if the OPTIONAL MATCH does any significant work before its WHERE is executed. The profile I get in my version of neo4j shows that the WHERE filtering is done before the OPTIONAL MATCH does any real work.

Upvotes: 5

Bruno Peres
Bruno Peres

Reputation: 16365

Try installing APOC procedures and using apoc.when.

Considering these parameters:

:params {ownerDecisionId:10, name:'Jon',executeOptionalMatch:true}

You can run a query like this:

MATCH (d:Decision)<-[:DEFINED_BY]-(ch:Characteristic) 
WHERE d.id = {ownerDecisionId} and ch.lowerName = LOWER({name}) 
CALL apoc.when({executeOptionalMatch}, 'OPTIONAL MATCH (ch)-[rcho:CONTAINS]->(cho:CharacteristicOption) RETURN rcho, cho', '', {ch:ch}) YIELD value
RETURN ch, value.rcho, value.cho

The OPTIONAL MATCH will be executed only when ownerDecisionId = true.

Note: remember to install APOC procedures according the version of Neo4j you are using. Take a look in the Version Compatibility Matrix.

Upvotes: 3

Related Questions