Take detour if relationship between two nodes is missing and choose detour node on node property base

I do have a tree like hierarchically structure in my graph as seen in this image:

I am querying for 4 connected nodes with the relationship "GLOR".
In some cases the "GLOR" relationship between node 3 and 4 is missing.
In this case i want to go up to the Level node (:LEAF) to look for neighbours of 3 which are connected to node 4 and do have the relationship "GLOR" as well.

How does the cypher query for this "if rel does not exist, take detour over level node to next leaf" look like?
Especially it should be dynamic so the "missing link" can be found between any two nodes of the searched path.

My approach looks like this:

MATCH nod1 = ((tp {tpid: 4, tpv: 1})<-[r1:TPH {seq: 1}]-(h1:Hierarchy)<-[pc1:PC*1..4]-()<-[hl1:LEAF]-(l1:Leaf {leaf: "ablaufgebrechen"}))
MATCH nod2 = ((tp)<-[r2:TPH {seq: 2}]-(h2:Hierarchy)<-[pc2:PC*1..4]-()<-[hl2:LEAF]-(l2 {leaf: "stiegenhaus"}))
MATCH nod3 = ((tp)<-[r3:TPH {seq: 3}]-(h3:Hierarchy)<-[pc3:PC*1..4]-()<-[hl3:LEAF]-(l3 {leaf: "generali elementar"})) 
MATCH nod4 = ((tp)<-[r4:TPH {seq: 4}]-(h4:Hierarchy)<-[pc4:PC*1..4]-()<-[hl4:LEAF]-(l4 {leaf: "coverage: rohrbruch leitungswasseraustritt frostschäden [measurevs]"}))
OPTIONAL MATCH (l1)-[p1:GLOR{tpv:1}]-(l2) 
OPTIONAL MATCH (l2)-[p2:GLOR{tpv:1}]-(l3) 
OPTIONAL MATCH (l3)-[p3:GLOR{tpv:1}]-(l4)
//OPTIONAL MATCH path0 = ((l3)-[:LEAF]->(:Level)<-[:LEAF]-(helper:Leaf)-[:GLOR]->(l4))
OPTIONAL MATCH (l4)-[o:GLOR{tpv:1}]->(q:Qualifikation)
RETURN *

Using the commented line as well will display all nodes from the "unknown" Level node which connect to the 4th node.


This commented line is not dynamic and only applicable if i already know where the link is missing and it returns all possible nodes. In a next step i would want to choose the best out of this possible nodes depending on a maximum node property for example

  • neo4j version 4.1.3, browser version