Search code examples
sqlneo4jcypherneo4j-apoc

Dynamic Neo4j Cypher Query


Is there a way to write the below neo4j cypher script to handle n case whens depending on the size of the array being read? I have varying array sizes on which to calculate co2 consumption so to use a one size fits all case when would be highly inefficient.

MATCH paths = allShortestPaths((a: Flights {label: 'Paris'})-[: FLIGHT*]->(b:Flights {label: 'Sydney'}))
WITH paths, relationships(paths) AS rels
UNWIND rels AS rel
WITH paths, 
 collect(rel.co2) AS co2, 
 collect(rel.engine_consumption) as ec
RETURN 
  reduce(acc1=0.0,
      x IN range(0, size(fc)-1) |
            case when x=0 then acc1 + co2[x]
                  when x=1 then acc1 + co2[x] * ec[x-1]
                  when x=2 then acc1 + co2[x] * ec[x-1] * ec[x-2]
                  when x=3 then acc1 + co2[x] * ec[x-1] * ec[x-2] * ec[x-3] 
                  ...
                  when x=size(ec)-1 then acc1 + co2[x] * ec[x-1] * ... * ec[0] 
                  end
      )  AS normalised_co2
;

Solution

  • I did this in the end using the python library py2neo, and created the cypher query using python

    case_when = ''
    accumulator = ''
    for x in range(max_paths):
        accumulator += f'* co2[{x}]'
        case_when += f'when x={x+1} then acc + co2[{x+1}]' + accumulator + ' \n '