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
.
Related videos on Youtube
Comments
-
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 over 9 yearsdon'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 over 9 yearshmmm, 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
zeroMessages
? -
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 over 9 yearsIf 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 about 5 yearsHow 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.