How can I use the `with` statement with `call.apoc.do.when` in Neo4j?

Viewed 1882

Firstly, you can create sample nodes with following commands,

CREATE (t1:Title { tid: '123abc'})
CREATE (t2:Title { tid: '123def'})
CREATE (t3:Title { tid: '123456'})
CREATE (t4:Title { tid: '123789'})
CREATE (u:User { pid: '456def'})

CREATE (t1)-[r:TO]->(t2)
CREATE (t2)-[r:TO]->(t3)
CREATE (t3)-[r:TO]->(t4)
CREATE (u)-[r:LIKE]->(t3)

Here is the graph,

graph

I have a query like that in Neo4j,

MATCH (t1:Title)-[r:TO]->(t2:Title)
WHERE t1.tid = '123abc'
AND NOT exists((t2)<-[:LIKE|:DISLIKE|:LOVE]-(:User {pid: '456def'}))
WITH COLLECT(r) AS rels
LIMIT 1

WITH rels
CALL apoc.do.when(
    SIZE(rels) > 0,
    'RETURN REDUCE(total = 0, x IN rels | total + x.weight) AS result',
    'RETURN 0 AS result'
) YIELD value
RETURN value.result

I want to use rels variable in do.when blog. There is a no problem for SIZE(rels) > 0 expression, but in if statement returns error like that,

Failed to invoke procedure apoc.do.when: Caused by: org.neo4j.exceptions.SyntaxException: Variable rels not defined (line 1, column 31 (offset: 30)) "RETURN REDUCE(total = 0, x IN rels | total + x.weight) AS result"

I'm newbie in Neo4j. I think, there is a special case for REDUCE. How can I solve this problem? Thanks in advance.

2 Answers

The sum can be directly obtained using the aggregation function SUM:

MATCH (t1:Title)-[r:TO]->(t2:Title)
WHERE t1.tid = '123abc' AND NOT EXISTS((t2)<-[:LIKE|:DISLIKE|:LOVE]-(:User {pid: '456def'}))
RETURN SUM(r.weight) AS result

Looking at the documentation, you can add a third parameter that includes parameters for inners statements:

MATCH (t1:Title)-[r:TO]->(t2:Title)
WHERE t1.tid = '123abc'
AND NOT exists((t2)<-[:LIKE|:DISLIKE|:LOVE]-(:User {pid: '456def'}))
WITH COLLECT(r) AS rels
LIMIT 1

WITH rels
CALL apoc.do.when(
    SIZE(rels) > 0,
    'RETURN REDUCE(total = 0, x IN rels | total + x.weight) AS result',
    'RETURN 0 AS result',
    {rels:rels}
) YIELD value
RETURN value.result
Related