Search code examples
loopsneo4jcypherneo4j-apoc

Cypher - How to call a procedure multiple times in loop?


In Neo4j Browser, I tried to call a procedure multiple times in a loop, but Neo4j reported the same error: Query cannot conclude with CALL (must be RETURN or an update clause). Specifically,

UNWIND [10, 20] AS age_num
MATCH (n:User {name: 'a', age: age_num})
CALL apoc.nodes.delete(n)

...got Neo.ClientError.Statement.SyntaxError:

Query cannot conclude with CALL (must be RETURN or an update clause) (line 3, column 1 (offset: 68))
"CALL apoc.nodes.delete(n)"
 ^
CALL apoc.periodic.iterate(
    "UNWIND [10, 20] AS age_num MATCH (n:User {name: 'a', age: age_num}) RETURN n",
    "CALL apoc.nodes.delete(n)",
    {batchMode: 'SINGLE', parallel: false}
)

...got errorMessages:

{
  "Query cannot conclude with CALL (must be RETURN or an update clause) (line 1, column 15 (offset: 14))\r\n\" WITH $n AS n CALL apoc.nodes.delete(n)\"\r\n               ^": 1
}

The procedure apoc.nodes.delete() here is just an example. Please don't advise me on using DETACH DELETE instead.

Question: In Cypher, how is it supposed to call a procedure multiple times in a loop, each time might have a different parameter, e.g. a different property value?

Environment: Neo4j Desktop v4.0.4, Windows 8.1 x64.


Solution

  • You have to add a RETURN statement at the end of the query like the error states. Basically, if you only call a single procedure, then cypher won't bug you with this. But if you do any kind of MATCH before a procedure call, you have to end the query with RETURN. You could also just use DETACH DELETE cypher statement instead.

    Version with DETACH DELETE:

    UNWIND [10, 20] AS age_num
    MATCH (n:User {name: 'a', age: age_num})
    DETACH DELETE n
    

    Version with APOC:

    UNWIND [10, 20] AS age_num
    MATCH (n:User {name: 'a', age: age_num})
    CALL apoc.nodes.delete(n) YIELD value
    RETURN distinct 'done'
    

    Edit: I have fixed the output as per the OP comment