Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j - Count distinct nodes

I have this kinds of relationships:

(:User)<-[:MENTIONS]-(:Tweet)-[:ABOUT]->(:Topic)

I would like to count all the users mentioned in the tweets regarding some topic.

With the following query

match (n:Topic)<--(t:Tweet)-[:MENTIONS]->(u:User) 
where n.name='politics'
return distinct count(u)

all I get is the relationships count.

What I would like to get is, instead, the number of users mentioned (without duplicates if a user is mentioned several times). How is that possible?

like image 859
sirdan Avatar asked Nov 29 '17 10:11

sirdan


People also ask

How do you count nodes in Neo4j?

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.

What is distinct Neo4j?

DISTINCT retrieves only unique rows depending on the columns that have been selected to output. The node named "B" is returned by the query, but only once.

What is optional match in Neo4j?

An OPTIONAL MATCH matches patterns against your graph database, just like a MATCH does. The difference is that if no matches are found, OPTIONAL MATCH will use a null for missing parts of the pattern. OPTIONAL MATCH could be considered the Cypher equivalent of the outer join in SQL.

How many nodes can a single relationship connect?

A relationship connects two nodes — a start node and an end node. Just like nodes, relationships can have properties. Relationships between nodes are a key part of a graph database.


1 Answers

Try putting distinct inside count function, this way:

match (n:Topic)<-[:ABOUT]-(t:Tweet)-[:MENTIONS]->(u:User) 
where n.name='politics'
return count(distinct u)
like image 72
Bruno Peres Avatar answered Oct 16 '22 17:10

Bruno Peres