Search code examples
neo4jcypher

How do I do multiple OPTIONAL MATCH in parallel in Cypher?


I am currently doing something like:

MATCH (s:Something)
OPTIONAL MATCH (t:Tag)<-[:HAS_TAG]-(s)
OPTIONAL MATCH (i:Item)<-[:HAS_ITEM]-(s)
OPTIONAL MATCH (w:Whatever)<-[:HAS_WHATEVER]-(s)

When I do a profile, I see that 3 optional expand for each OPTIONAL MATCH sequentially, wonder if I can speed it up by possibly doing it in parallel? Since its independent of each other?


Solution

  • in these cases I often do

    MATCH (s:Something)
    WITH s,
         [(s)-[:HAS_TAG]->(t:Tag) | t] AS ts,
         [(s)-[:HAS_ITEM]->(i:Item) | i] AS is,
         [(s)-[:HAS_TAG]->(w:Whatever) | w] AS ws
    

    which returns arrays, instead of null in case the OPTIONAL MATCH does not return anything. and often it's faster too.