Fallback to secondary query if first fails to match

I have a model a bit like this:


Most Systems do not have a direct budget associated because most are funded via a team, but where the direct relationship is specified it takes precedence, falling back to the team Budget where the direct Budget is not defined

I'm struggling to write a query which has this fallback behaviour.

In pseudo code I want:

try {
    MATCH (b:Budget)-[:PAYS_FOR]->(s:System)
    WHERE s.code = "my-code"
    RETURN b
} catch {
    MATCH (b:Budget)-[:PAYS_FOR]->(:Team)<-[:DELIVERED_BY]-(s:System)
    WHERE s.code = "my-code"
    RETURN b

How do achieve such conditional choice of query?

Hi @wheresrhys ,

Yeah we can do that . for this you need to use below apoc procedure . this will work as if else .

apoc would be like this.

OPTIONAL MATCH (b:Budget)-[:PAYS_FOR]->(s:System) WHERE s.code = "my-code"with b
CALL apoc.when(b IS NOT NULL,"MATCH (b:Budget)-[:PAYS_FOR]->(s:System) WHERE s.code = 'my-code'RETURN b" ,"MATCH (b:Budget)-[:PAYS_FOR]->(:Team)<-[:DELIVERED_BY]-(s:System) WHERE s.code = 'my-code' RETURN b") yield value
Return value

Please run and let us know this is solving your query or not.

1 Like

Thanks Kunal.

I'm surprised it's not possible without APOC though.

Reading the solution you give, it looks like it executes the initial query twice in the case where the PAYS_FOR relationship exists on the System node. Is there some way to just reuse the reslt of the original query?

Usually you would do that on the client side.

You can probably also try to use UNION with the two statements

1 Like

The client is neo4j-graphql-js, and I'd like to use the @cypher directive to populate this field in get requests

Hmm ok, would you mind creating an issue in APOC so we can look into thatt