Search code examples
neo4jcypher

Neo4j Cypher Pattern comprehension in return statement


I need to add to my Cypher query's return statement the following Pattern comprehension:

[ (rc:Criterion) WHERE rc.id IN childD.replaceableCriterionIds | {entity: rc} ] AS decisionReplaceableCriteria

but it fails with the following exception:

Caused by: org.neo4j.driver.exceptions.ClientException: Invalid input 'WHERE': expected "-", "<", <ARROW_LEFT_HEAD> or <ARROW_LINE> 

It only works when I'm adding the redundant relationship with another node

[ (rc:Criterion)-[:CREATED_BY]->(:User) WHERE rc.id IN childD.replaceableCriterionIds | {entity: rc} ] AS decisionReplaceableCriteria

The following part is absolutely redundant for my needs:

-[:CREATED_BY]->(:User)

Is it possible to rewrite my pattern comprehension to avoid such redundant syntax?


Solution

  • If you are using Neo4j 5.6+, you can use the COLLECT subquery. Here is a sample snippet:

    ...
    RETURN COLLECT {
        MATCH (rc:Criterion)
        WHERE rc.id IN childD.replaceableCriterionIds
        RETURN {entity: rc}
    } AS decisionReplaceableCriteria
    

    In prior versions of Neo4j, you can try a hack:

    ...
    RETURN [ (rc:Criterion)-[*0]->() WHERE rc.id IN childD.replaceableCriterionIds | {entity: rc} ] AS decisionReplaceableCriteria
    

    This uses a variable-length path pattern specifying a length of 0. If you want to see if this variable-length path pattern causes any DB hits, PROFILE your query and look at the VarLengthExpand operation's "db hits".