Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group and count relationships in cypher neo4j

Tags:

neo4j

cypher

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
like image 368
Astronaut Avatar asked Dec 17 '14 23:12

Astronaut


People also ask

How do you perform and aggregation in Cypher?

The Cypher query offers aggregation similar to GROUP BY offered by SQL. The aggregate function can take multiple values and can calculate the aggregated values for them. In this recipe, we will learn the common aggregation techniques, with the help of examples.

Which of the given below query is used to return the count of the relationship for a node?

Using count(*) to return the number of nodes The function count(*) can be used to return the number of nodes; for example, the number of nodes connected to some node n . The labels and age property of the start node n and the number of nodes related to n are returned.

How many nodes a single relationship can connect?

Relationships. Relationships organize the nodes by connecting them. A relationship connects two nodes — a start node and an end node. Just like nodes, relationships can have properties.


1 Answers

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.

like image 105
Dave Bennett Avatar answered Oct 21 '22 02:10

Dave Bennett