Phil Christensen
Phil Christensen

Reputation: 26

Cypher query to find nodes, then find counts of those nodes that have a particular relationship

I'm using neo4j to represent employers and their health benefit offerings. ie :

(client)-[OFFERED_PLAN]->(planOffering)-[HAS_PLAN_DETAIL {value:number}]->(benefitPlanType)

I'm trying to query this graph to get the top 50 clients in CA, then to get the number of those 50 clients that offer a medical plan (value = 1) and how many offered dental (value = 5). I've tried many variations of the below query, but I think this is the closest. The output of this will currently return the same number for all three variables, 25, which is the number of these clients offering dental.

MATCH (client:Client)-[:LOCATED_IN]->(:State {stateCode:'CA'})
LIMIT 50
with client as mc, client as dc, client
MATCH (mc)-[:OFFERED_PLAN]->(mp:PlanOffering)-[mbpt:HAS_PLAN_DETAIL]->(:BenefitPlanType),
      (dc)-[:OFFERED_PLAN]->(:PlanOffering)-[dbpt:HAS_PLAN_DETAIL]->(:BenefitPlanType)
WHERE mbpt.value = 1 and dbpt.value = 5
with  count(distinct(client.clientID)) as clientCount,  
      count(distinct(mc.clientID)) as numberMedicalClients,  
      count(distinct(dc.clientID)) as numberDentalClients
return *

Upvotes: 1

Views: 44

Answers (1)

Luanne
Luanne

Reputation: 19373

Can't test this query but if you simply aggregate the clients by the plan value, then you'd get the number of clients on each plan, without having to re-match them

MATCH (client:Client)-[:LOCATED_IN]->(:State {stateCode:'CA'})
WITH client LIMIT 50
MATCH (client)-[:OFFERED_PLAN]->(mp:PlanOffering)-[mbpt:HAS_PLAN_DETAIL]->(:BenefitPlanType)
WHERE mbpt.value IN [1,5]
RETURN mbpt.value, count(*)

Upvotes: 4

Related Questions