gravatasufoca
gravatasufoca

Reputation: 39

Neo4j count the number of related nodes

I'm starting studying the Neo4j and the Cypher Queries, and I need some help to understand and get some results.

I have this MATCH query:

MATCH (p:EntidadePessoa {id: 168750})-[rd:SE_RELACIONA]->(d:Documento)<--(p2) 
 where p2:EntidadePessoa or p2:EntidadeOrganizacao 
 return p,d,p2

That results this:

graph image

Commencing with EntidadePessoa id:168750, I want the count of EntidadeDocumento directcly linked to EntidadePessoa id:168750, is this case 2, and the count of each Entidade* that is linked to EntidadeDocumento, in this case 4 for each EntidadeDocumento.

I tried some queries, but none give me the results I wanted, the count number is never the numbers I wanted.

Could you help with that?

Upvotes: 0

Views: 1032

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12704

This will give you the result. This is similar to count and group_by in sql.

 MATCH (p:EntidadePessoa {id: 168750})-[rd:SE_RELACIONA]->(d:Documento)<--(p2) 
  where p2:EntidadePessoa or p2:EntidadeOrganizacao 
 With p, count(distinct d) as cnt_d, count(p2) as cnt_p2
  return p, cnt_d, cnt_p2

Upvotes: 0

Thennan
Thennan

Reputation: 898

  1. A query to get the count of d nodes connected to p (id: 168750).
    MATCH (p:EntidadePessoa {id: 168750})-[rd:SE_RELACIONA]->(d:Documento)
    RETURN p.id as `nodeId`, count(d) as `connectedCount`

output:

nodeId    connectedCount
168750    2
  1. A query with a subquery to look at just d:Documento, incoming links from p2, omitting (p:EntidadePessoa {id: 168750}) and counting p2s for each d node:
    CALL
    {MATCH (p)-[rd:SE_RELACIONA]->(d:Documento)
    WHERE p.id=168750
    RETURN  d,p.id as `topid`}
    MATCH (p2)-->(d)
    WHERE (p2:EntidadePessoa or p2:EntidadeOrganizacao) AND p2.id<>topid
    //p2.id<>topid ensures p is not included in count(p2) 
    RETURN d.id as `nodeId`, count(p2) as `connectedCount`

output:

nodeId    connectedCount
164532    4
164552    4
  1. Combine both these results with a UNION:
    MATCH (p:EntidadePessoa {id: 168750})-[rd:SE_RELACIONA]->(d:Documento)
    RETURN p.id as `nodeId`, count(d) as `connectedCount`UNION
    CALL
    {MATCH (p)-[rd:SE_RELACIONA]->(d:Documento)
    WHERE p.id=168750
    RETURN  d,p.id as `topid`}
    MATCH (p2)-->(d)
    WHERE (p2:EntidadePessoa or p2:EntidadeOrganizacao) AND p2.id<>topid
    //p2.id<>topid ensures p is not included in count(p2) 
    RETURN d.id as `nodeId`, count(p2) as `connectedCount`

output:

nodeId    connectedCount
168750    2
164552    4
164552    4

Upvotes: 1

Related Questions