Search code examples
chartsneo4jcypher

Make complex query neo4J (Cypher) for filtring result


I have 4 Types of nodes:

A it the start point  
B  
C  
D final destination points

see this image

I want to display some node D. with these steps:

  1. When we go with node A to node B I want to explore node B when r.val < 5 for example So in this example I want to explore B2
  2. Then I want to explore all Nodes B attached to B when its attached to the same Node C (for example when C nom:Travail), in my example its B1 and B4
  3. In the last I want to suggest Nodes D ORDER BY r.s (score between B nodes) (in my example the relationship between B2 - B1 and B2 - B4)

So I want the result are id of D6 and D7 ( ana and moa)

I take this code:

MATCH (a:A1{name: "bale"})-[r1]->(b:B) 
MATCH (b)-[r2]-(b2:B)
WHERE r1.val < 3 
WITH DISTINCT b.name AS skill_k_1 , a AS a, r1 AS r1, b AS b, r2 AS r2,b2 AS b2
MATCH (b:B{name:skill_k_1})-[r3]-(cat:C)
WITH DISTINCT cat.nom AS cat_k_1, a AS a, r1 AS r1, b AS b, r2 AS r2 ,b2 AS b2, r3 AS r3, cat AS cat
MATCH (b2)-[r]-(b3:B)-[r4]-(cat2:C{nom:cat_k_1})
MATCH (b3)-[r5]-(d:D)
RETURN d.id ORDER BY r.s

My code display doesn't select just the node who attached to C where C.nom == Travail but he select all nodes and it suggest ALL nodes D not just D6 and D7


Solution

  • If i understood correctly, i think this query should work:

    MATCH (a:A1 {name: "bale"})-[r1]->(b:B)-[r2]-(c:C), // match a node (a:A1) linked to (b:B) linked to (c:C)
        (b2:B)-[r3]-(c), // match a node b2 with the same node (c:C)
        (b)-[r4]-(b2) // and with a relationship between b and b2
    
    WHERE r1.val < 5 // where first relationship has a val < 5
    with b2, r4.s as score // get the b2 and the score between the 2 (:B) nodes
    match (b2)-[r1]-(d:D) // look for a (:D) node
    return d.id order by score // return id order by score
    

    It's not clear to me what is :SKILL label, (maybe all :B nodes have the SKILL label as well?) but I guess your query doesn’t work because the MATCH (b2)-[r]-(b3:SKILL) part get ALL b3 nodes with a label SKILL related to b2, without any match-filter.