Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find most common property - cypher

Tags:

neo4j

cypher

Is there a way I can use cypher to derive the most common (and second most common) property value of a particular node type?

At the moment I am identifying the different values for the property:

MATCH(a:Label1)-[r:REL]->(b:Label2) RETURN DISTINCT b.prop; 

And then counting them individually:

MATCH(a:Label1)-[r:REL]->(b:Label2) WHERE b.prop = "x" RETURN COUNT(x); 

Any help would be appreciated, I am using Neo4j 3.0.0.

I'm not sure how to combine these queries.

like image 780
mixiul__ Avatar asked Dec 14 '22 06:12

mixiul__


2 Answers

It is as easy as :

MATCH (a:Label1)-[r:REL]->(b:Label2)
RETURN b.prop, count(*) as occurences
ORDER BY occurences DESC
LIMIT 2

You can read about automatic aggregation here : http://neo4j.com/docs/stable/query-aggregation.html

like image 139
Christophe Willemsen Avatar answered Dec 22 '22 04:12

Christophe Willemsen


You can use the keys() function to get the properties from each matching node. This returns a collection of keys for that node. Unwind the collections and aggregate the counts for each property accross all matching nodes.

MATCH (a:Label1)-[r:REL]->(b:Label2)
UNWIND keys(b) as prop
RETURN prop, count(*) as num_props
ORDER BY num_props desc
like image 44
Dave Bennett Avatar answered Dec 22 '22 03:12

Dave Bennett