Sunday, December 20, 2020

Conditional Cypher Execution

Sometimes queries require conditional execution logic that can’t be adequately expressed in Cypher. The conditional execution procedures simulate an if / else structure, where a supplied boolean condition determines which cypher query is executed.


WHEN Procedures

For if / else conditional logic, when procedures allow an ifQuery and elseQuery to be specified. If the conditional is true, the ifQuery will be run, and if not the elseQuery will be run.


CALL apoc.when(

  condition: Boolean,

  ifQuery: String,

  elseQuery: String,

  params: Map)

YIELD value


CALL apoc.do.when(

  condition: Boolean,

  ifQuery: String,

  elseQuery: String,

  params: Map)

YIELD value


For example, if we wanted to match to neighbor nodes one and two traversals away from a start node, and return the smaller set (either those one hop away, or those that are two hops away), we might use:



MATCH (start:Node)-[:REL]->(a)-[:REL]->(b)

WITH collect(distinct a) as aNodes, collect(distinct b) as bNodes


CALL apoc.when(

  size(aNodes) <= size(bNodes),

  'RETURN aNodes as resultNodes',

  'RETURN bNodes as resultNodes',

  {aNodes:aNodes, bNodes:bNodes})

YIELD value


RETURN value.resultNodes as resultNodes



CASE Procedures

For more complex conditional logic, case procedures allow for a variable-length list of condition / query pairs, where the query following the first conditional evaluating to true is executed. An elseQuery block is executed if none of the conditionals are true.



CALL apoc.case(

  conditionals: List of alternating Boolean/String,

  elseQuery: String,

  params: Map)

YIELD value




If we wanted to MATCH to selection nodes in a column, we could use entirely different MATCHES depending on query parameters, or based on data already in the graph:



MATCH (me:User {id:$myId})

CALL apoc.case([

  $selection = 'friends', "RETURN [(me)-[:FRIENDS]-(friend) | friend] as selection",

  $selection = 'coworkers', "RETURN [(me)-[:WORKS_AT*2]-(coworker) | coworker] as selection",

  $selection = 'all', "RETURN apoc.coll.union([(me)-[:FRIENDS]-(friend) | friend], [(me)-[:WORKS_AT*2]-(coworker) | coworker]) as selection"],

  'RETURN [] as selection',

  {me:me}

)

YIELD value

RETURN value.selection as selection;




References:

https://neo4j.com/labs/apoc/4.1/cypher-execution/conditionals/




1 comment: