问题描述
有没有办法编写下面的 Neo4j 密码脚本来处理 n 种情况,具体取决于正在读取的数组的大小?我有不同的数组大小来计算 co2 消耗,因此在效率非常低的情况下使用一种大小适合所有情况。
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
;
解决方法
我最后使用 python 库 py2neo 做到了这一点,并使用 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 '