priyanka.sarkar
priyanka.sarkar

Reputation: 26538

How to write the below Cypher queries on Node Relationships?

I have a sample database as under

CREATE (Prod1:TestProdNeoForJ {productname:'Product1'})
CREATE (A:Person {name:'A S'})
CREATE (R:Person {name:'R B'})
CREATE (L:Person {name:'L R P'})
CREATE (P:Person {name:'P R'})
CREATE (G:Person {name:'G K'})
CREATE (RK:Person {name:'R K'})


CREATE  
    (A)-[:WORKS_IN {roles:['Technical Lead']}]->(Prod1),    
    (R)-[:WORKS_IN {roles:['Technical Lead']}]->(Prod1),    
    (L)-[:WORKS_IN {roles:['Senior Developer']}]->(Prod1),
    (P)-[:WORKS_IN {roles:['Junior Project Manager']}]->(Prod1),    
    (G)-[:WORKS_IN {roles:['Senior Project Manager']}]->(Prod1),
    (A)-[:REPORTS_TO {roles:['Technical Lead']}]->(G),
    (R)-[:REPORTS_TO {roles:['Technical Lead']}]->(G),
    (P)-[:REPORTS_TO {roles:['Junior Project Manager']}]->(G),
    (G)-[:REPORTS_TO {roles:['Senior Project Manager']}]->(RK),
    (RK)-[:DH]->(Prod1)

enter image description here

I am looking for the below cypher queries on the Relationships

a) Peoples reporting to 'G'

(the answer will be: A,R,P)

b) Peoples reporting to 'G' whose roles are 'Technical Lead'

(the answer will be: A,R)

c) Peoples directly reporting to 'RK'

(the answer will be: G)

d) Peoples directly/indirectly reporting to 'RK'

(the answer will be: G,P,R,A) since A, R, P reports to G and G directly reports to RK

What I have tried so far (for the first one):

var query = WebApiConfig.GraphClient.Cypher
          .Match("(m:TestProdNeoForJ)")
          .OptionalMatch("(a:Person)-[r1:REPORTS_TO]->(b:Person)")
          .Return((a, b) => new
          {                  
              cast = Return.As<string>("collect(a.name)")
          })
          .Limit(100);
var data = query.Results.ToList();

The cypher is producing the result as (of course because I have to restrict till G).

[
  "A S",
  "R B",
  "P R",
  "G K"
]

Upvotes: 0

Views: 36

Answers (1)

Stefan Armbruster
Stefan Armbruster

Reputation: 39925

a)

MATCH (p:Person)-[:REPORTS_TO]->(:Person{name:'G K'}) RETURN p

b)

MATCH (p:Person)-[r:REPORTS_TO]->(:Person{name:'G K'})
WHERE 'Technical Lead' IN r.roles 
RETURN p

Since you've choosen to use an array property for roles you need to check if 'Technical Lead' is part of that array using IN. Depending on the use case it might make sense to model the roles as separate nodes.

c)

MATCH (p:Person)-[:REPORTS_TO]->(:Person{name:'R K'}) RETURN p

Basically the same as a) .

d)

MATCH (p:Person)-[:REPORTS_TO*]->(:Person{name:'R K'}) RETURN p

This uses a variable path length expression *.

Upvotes: 1

Related Questions