cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Fallback to secondary query if first fails to match

I have a model a bit like this:

(:Budget)-[:PAYS_FOR]->(:System)-[:DELIVERED_BY]->(:Team)<-[:PAYS_FOR]-(:Budget)

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?

5 REPLIES 5

12kunal34
Graph Fellow

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.

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

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