8
votes

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
2
I am having a little trouble understanding exactly. Is n the author and m the post? If the relationship, r, is :POSTED why do you need to equate n.id = m.sender_id? If what you have really something like this... (a:Author)-[r:POSTED]->(m:Message)?Dave Bennett
sorry wrong copy paste... I will edit it. Ok, I corrected it.Astronaut
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.Michael Hunger

2 Answers

11
votes

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.

-1
votes

I get reuslt with

match () -[r]->() return type(r), count(type(r))

enter image description here