Search code examples
neo4jcypher

Neo4j APOC custom function hangs when nothing is found


I have written the following custom function that performs a complex search and returns a list of IDs. Here is a simplified version:

CALL apoc.custom.declareFunction('test()::LIST OF INTEGER?', '
    MATCH (m:Movie)
    WITH m.id AS id
    LIMIT 1
    RETURN id
')

The function is intended to be used in the following query:

MATCH (m:Movie)
WHERE m.id IN custom.test()
RETURN m.title AS title

When testing the function with RETURN custom.test() as ids, the execution result is [{'ids': [57]}]

In the case where the function finds nothing (for the simplified version, I replace LIMIT 1 with LIMIT 0), I expect the function to return [{'ids': []}]. However, instead, it simply hangs.

I have tried defining the return type as both LIST OF INTEGER and LIST OF INTEGER?.

Is this an APOC bug? How can I resolve this issue?


Solution

  • Although adding OPTIONAL to the MATCH statement indeed helped to avoid hanging, this approach is only applicable to MATCH, not to CALL.

    I propose a general solution: At the end of the query, we should collect all the results into an array using COLLECT() and create the function with the parameter forceSingle = true:

    CALL apoc.custom.declareFunction('test(limit :: INTEGER)::LIST OF INTEGER?', '
    MATCH (m:Movie)
    WITH m.id AS id
    LIMIT $limit
    RETURN COLLECT(id)
    ', true)
    

    Now, calling the function RETURN custom.test(0) as ids returns [{'ids': []}].