Astronaut
Astronaut

Reputation: 7031

How to group and count relationships in cypher neo4j

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

Upvotes: 9

Views: 15042

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

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.

Upvotes: 14

Related Questions