Running a conditional query with optional match

Hi
I have the following query:

OPTIONAL MATCH (s:GraphTarget {AppId:$AppId})-[e0:OwnerOf]->(a:Source)-[e1 {Verified:true}]-(i:Source) 
  WITH s AS s, e0 AS e0, a AS a, e1 AS e1, i AS i limit 100
OPTIONAL MATCH(s)-[my0:MyInstitutes]-(ins0:Institutes)-[be0:BeenAt]-(in0:Institute)
  RETURN *

This query return 10MB of results to the client (most of them are duplicated).
When removing any one of the OPTIONAL MATCH from the query, the result returned is relatively small (100+ nodes).

The second OPTIONAL MATCH is there just in case the first one did not return any result, so only then I need to run the second one. The second one is really really small, 3 nodes.

Is it possible to run the second OPTIONAL MATCH only if the first one did not return any results?
if not, what are my options here to run it all in a single query?

Thanks

I’ve simplified the query a bit…

Please try:

"MATCH (s:GraphTarget {AppId:$AppId}) WITH s AS s OPTIONAL MATCH (s)-[e0:OwnerOf]->(a:Source) WITH s AS s, e0 AS e0, a AS a LIMIT 100 WITH s AS s, e0 AS e0, a AS a, count(a) AS c OPTIONAL MATCH(s)-[my0:MyInstitutes]->(ins0:Institutes) WHERE c = 0 RETURN *"

The idea here is to count the number of records from the first OPTIONAL MATCH and run the second OPTIONAL MATCH if the count is 0.

Hey. your trick is very useful, I’ve actually implemented it in another use case.
But, my current situation is a little bit different.

CYPHER AppId=1904 
MATCH (g: GraphTarget {AppId:$AppId})-[oo:OwnerOf]->(s:Source) with g,oo,s
OPTIONAL MATCH(s)-[e1 {Verified:false}]-(i:Source) with i,g,oo,e1,s limit 100 
OPTIONAL MATCH(g)-[my0:MyInstitutes]-(ins0:Institutes)-[be0:BeenAt]-(in0:Institute) with distinct s, oo, i, g, e1, be0, ins0, my0,in0
RETURN *`

Yesterday I tried to simplify my question and I think I skewed the picture a little bit.
Anyway, the last OPTIONAL MATCH (which is needed) is causing a mass duplication (exponential).

When the limit statement is 1, I get no duplication, when its 100 getting 1000 duplications.
The query result reflected on the graph is ok, be the duplications are causing server outage. especially when i want the limit to be 500.
I have tried to distinct every column in the last OPTIONAL MATCH with no success…

Thank you for your fast reply yesterday.
Below you can get a feeling of the duplication…


Avi

Please try:

CYPHER AppId=1904
MATCH (g: GraphTarget {AppId:$AppId})-[oo:OwnerOf]->(s:Source)
OPTIONAL MATCH p = (s)-[e1 {Verified:false}]-(i:Source)
RETURN g, oo, s, p LIMIT 100
UNION
MATCH (g: GraphTarget {AppId:$AppId})-[oo:OwnerOf]->(s:Source)
OPTIONAL MATCH p = (g)-[my0:MyInstitutes]-(ins0:Institutes)-[be0:BeenAt]-(in0:Institute)
RETURN g, oo, s, p