Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of relationships each node has in Cypher?

Tags:

neo4j

cypher

I am using a graph db (neo4j) and cypher. My goal for this query is to first match every Pin that a given User has PINNED, and then count the number of LIKES each of those pins has. Currently I am able to return the total number of likes between all the pins, but this information doesn't help me when there are several pins. For example, if I run this query in my DB right now and there are 2 nodes with 2 likes and 3 likes respectively, my query will return "5". So I have no way of knowing how many of the likes belong to each pin. How can I write this query such that I get the number of LIKES for each pin?

MATCH (u:User {lastName:"Example"})-[:PINNED]->(z:Pin)
WITH collect(z) as cs
MATCH (:User)-[:LIKES]->(y:Pin)
WHERE (y) in cs
MATCH (a:User)-[r:LIKES]->(y)
RETURN COUNT(r), y
like image 479
Graham Perich Avatar asked Jan 18 '17 04:01

Graham Perich


People also ask

How do you count nodes in Cypher?

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.

WHAT IS WITH clause in Cypher?

The WITH clause allows query parts to be chained together, piping the results from one to be used as starting points or criteria in the next. It is important to note that WITH affects variables in scope.


1 Answers

Looks like you're going a little overboard on matches, we can simplify this.

MATCH (u:User {lastName:"Example"})-[:PINNED]->(z:Pin)
RETURN z, SIZE( ()-[:LIKES]->(z) ) as likes
like image 111
InverseFalcon Avatar answered Oct 14 '22 03:10

InverseFalcon