How to group and count relationships in cypher neo4j

11,926

How about this?

MATCH (u:User)-[r:POSTED]->(m:Message)
RETURN id(u), count(m)
ORDER BY count(m)

Have you had a chance to check out the current reference card?

https://neo4j.com/docs/cypher-refcard/current/

EDIT:

Assuming that the relationship :POSTED is only used for posts then one could do something like this instead

MATCH (u:User {name: 'my user'})
RETURN u, size((u)-[:POSTED]->())

This is significantly cheaper as it does not force a traversal to the actual Message.

Share:
11,926

Related videos on Youtube

Astronaut
Author by

Astronaut

merge keep

Updated on September 16, 2022

Comments

  • Astronaut
    Astronaut over 1 year

    How can I quickly count the number of "posts" made by one person and group them by person in a cypher query?

    Basically I have message label nodes and users that posted (Relationship) those messages. I want to count the number of messages posted by each user.

    Its a group messages by sender ID and count the number of messages per user.

    Here is what I have so far...

    START n=node(*) MATCH (u:User)-[r:Posted]->(m:Message)
    RETURN u, r, count(r)
    ORDER BY count(r)
    LIMIT 10
    
    • Michael Hunger
      Michael Hunger over 9 years
      don't use start n=node(*) !! Esp. not with an unrelated node, it will create a huge cartesian product for every node in your graph.
  • Dave Bennett
    Dave Bennett over 9 years
    hmmm, i think i need more infomration. That is a pretty simple group by statement; I think I am still missing something from your requirement. There are users that post messages and you want the count of messages posted per user - no? Are you potentially misssing users that have :POSTED zero Messages?
  • Astronaut
    Astronaut over 9 years
    //top 10 posters MATCH (u:User)-[r:Posted]->(m:Message) RETURN u.fullname, count(r) ORDER BY count(r) desc Limit 10 Problem with my code was that I was using START
  • Astronaut
    Astronaut over 9 years
    If user has not posted any message I dont count him, its only a TOP 10 feature, without the limit it counts all the messages posted by all the users that Posted, so it works quite nicelly :) Thanks for your input. I am very sleepy now...
  • mingchau
    mingchau about 5 years
    How to group by the node and count the distinct relationships per every node? Since the each node could have the same relation ship(type & properties) with other nodes.