Search code examples
memgraphdb

How to do multiple MATCH in Memgraph?


Does Mempgrah support something like multiple matches? I keep running into an issue that produces result 0. I have several queries, when I run them one by one, I get some results back, but if I arrange them as multiple matches I end up with zero.

My code is:

MATCH (e:Employee {status:'initiated', id:'id-1'}), (o:Office {status:'initiated', id:'id-1'})
WITH COLLECT(e) + COLLECT(o) AS allEntities
MATCH (d:Gadget {status:'initiated', id:'id-1'}), (a:Alarm {status:'initiated', id:'id-1'})
WITH allEntities, COLLECT(d) + COLLECT(a) AS allDevices
RETURN size(allEntities)//, size(allDevices);

Solution

  • Could it be possible that one of your MATCH queries returns an empty set of results? Multiple MATCH clauses behave like a cartesian product and therefore return null if any of the results are an empty set.

    You can test this by running separate queries:

    MATCH (e:Employee {status:'initiated', id:'id-1'}), (o:Office {status:'initiated', id:'id-1'})
    WITH COLLECT(e) + COLLECT(o) AS allEntities
    RETURN size(allEntities);
    

    and then:

    MATCH (d:Gadget {status:'initiated', id:'id-1'}), (a:Alarm {status:'initiated', id:'id-1'})
    WITH COLLECT(d) + COLLECT(a) AS allDevices
    RETURN size(allDevices);
    

    If any of these queries returns 0 than that is probably your issue. You can fix this by adding OPTIONAL before MATCH. When using OPTIONAL MATCH empty results are allowed and are not affecting your end result.