I have a query that can return a potentially huge number of rows. It is extremely critical that it is as fast as possible.
Is there a way to change what is RETURNED based on what is matched? Here is a simplified version of the query:
MATCH p=(x)-[*]->(y) WHERE x.n="a"
WITH p,y OPTIONAL MATCH (y)<-[]-(z)
RETURN DISTINCT p,z
If the OPTIONAL MATCH finds results then there is no need for the large set 'p' to be returned.
What I would like to do with the results is:
IF z has results THEN RETURN z ELSE RETURN p
Thanks!
This query should work (it essentially produces 2 kinds of results):
MATCH p=(x)-[*]->(y) WHERE x.n="a"
OPTIONAL MATCH (y)<--(z)
RETURN DISTINCT
CASE WHEN z IS NULL THEN {p: p} ELSE {z: z} END AS res;
Note that unbounded patterns like [*]
can take a long time (or never finish, or run out of memory) if you have a lot of data.