Search code examples
neo4jcypherpy2neo

How do I count all the other nodes related to a specific node


The path is representing for users' browse history.

The upper path means there's one user who has browsed page A -> page B -> page C

The lower path means, one user browsed page X-> page Y -> page B -> page C

For example, If I want to calculate the relevance with page C

The expected anwser is on the table

Or if I want to find all the relevance with page B

the anwser should be

  • page A : 1
  • page X : 1
  • page Y : 1
  • page C : 0

How could I get the expected anwser with py2neo or cypher query


Solution

  • If your "b" nodes are different nodes, and thus you have complete distinct paths, this query works :

    MATCH (b:Page)
    WHERE b.id = 'b'
    MATCH (b)<-[:LINK_TO*..10]-(referer)
    RETURN referer.id, count(*)
    

    Result :

    y   1
    a   1
    x   1
    

    Test console here http://console.neo4j.org/r/sb5qmq

    Change 'b' by c to see that b will have a count of 2

    b   2
    y   1
    a   1
    x   1
    

    EDIT

    If your nodes 'b' are the same, you can do this :

    MATCH (b:Page { id:'b' })
    WITH b
    MATCH (p:Page)
    WHERE p <> b
    OPTIONAL MATCH (p)-[r:LINK_TO*..3]->(b)
    RETURN p.id, count(r)
    

    http://console.neo4j.org/r/prb2my