简体   繁体   中英

How to execute cypher query within a CASE WHEN THEN clause in Neo4j Cypher

I have a use case where I am trying to optimize my Neo4j db calls and code by using the RETURN CASE WHEN THEN clauses in Cypher to run different queries depending on the WHEN result. This is my example:

MATCH (n {email: 'abc123@abc.com'}) 
RETURN  
CASE WHEN n.category='Owner' THEN  MATCH '(n)-[r:OWNS]->(m)'  
WHEN n.category='Dealer' THEN MATCH (n)-[r:SUPPLY_PARTS_FOR]->(m) 
WHEN n.category='Mechanic' THEN MATCH (n)-[r:SERVICE]-(m) END 
AS result;

I am not sure this is legal but this is what I want to achieve. I am getting syntax errors like Invalid input '>'. How can I achieve this in the best manner? EDIT for possible APOC solution: This was my plan before discovering the limitation of FOREACH...

MATCH (user:Person {email:{paramEmail}})
FOREACH (_ IN case when 'Owner' = {paramCategory} then [1] else [] end|
SET user:Owner, user += queryObj 
WITH user, {paramVehicles} AS coll
UNWIND coll AS vehicle
MATCH(v:Vehicles {name:vehicle}) 
CREATE UNIQUE (user)-[r:OWNS {since: timestamp()}]->(v)
SET r += paramVehicleProps 
)
FOREACH (_ IN case when 'Mechanic' = {Category} then [1] else [] end|
SET user:Owner, user += queryObj 
WITH user, {paramVehicles} AS coll
….
)
FOREACH (_ IN case when 'Dealer' = {paramCategory} then [1] else [] end|
SET user:Owner, user += queryObj 
WITH user, {paramVehicles} AS coll
…...

)
RETURN user,
CASE {paramCategory}

WHEN 'Owner' THEN [(n)-[r:OWNS]->(m) | m and r]
 WHEN 'Dealer' THEN [(n)-[r:SUPPLY_PARTS_FOR]->(m) | m] 
WHEN 'Mechanic' THEN [(n)-[r:SERVICE]-(m) | m]
 END AS result`,{
 paramQueryObj: queryObj,
 paramVehicles: makeVehicleArray,
 paramVehicleProps: vehiclePropsArray,
 paramSalesAgent: dealerSalesAgentObjarray,
 paramWarehouseAgent: dealerWarehouseAgentObjarray
}).....

does anyone know to convert this using apoc.do.when()? note I need 'm' and 'r' in the first THEN.

You should still use a label in your first match, otherwise you get a full database scan and not a index lookup by email!!

for your query you can use pattern comprehensions:

MATCH (n:Person {email: 'abc123@abc.com'}) 
RETURN  
CASE n.category 
WHEN 'Owner'    THEN  [(n)-[r:OWNS]->(m) | m]
WHEN 'Dealer'   THEN [(n)-[r:SUPPLY_PARTS_FOR]->(m) | m] 
WHEN 'Mechanic' THEN [(n)-[r:SERVICE]-(m) | m] END 
AS result;

It is also possible to use apoc.do.case: https://neo4j.com/labs/apoc/4.4/overview/apoc.do/apoc.do.case/

CALL apoc.do.case([
  false,
  'CREATE (a:Node{name:"A"}) RETURN a AS node',
  true,
  'CREATE (b:Node{name:"B"}) RETURN b AS node'
  ],
  'CREATE (c:Node{name:"C"}) RETURN c AS node',{})
YIELD value
RETURN value.node AS node;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM