Reputation: 87
I have a question about Cypher query with neo4j database. Suppose that I have a number of nodes like (node:student{name:"Alice"}). How can I get the name that appear most frequently with cypher query?
I have a simple solution like:
MATCH (n:student)
RETURN n.name,count(*) as times
ORDER BY times DESC
LIMIT 1;
Is there another way to get the same result, without using ORDER BY and LIMIT clause? Such as any build-in function like MAX(),..etc
Upvotes: 3
Views: 1198
Reputation: 30407
max()
is for finding the maximum value across all rows, but you're not actually looking for this value alone, you want to use it to match to the row in question with that max value.
And to get max()
, you need to aggregate the rows so it considers the max of all of them (the non-aggregation variables become the grouping key, and if all variables are aggregations then it considers the full set). At that point you can filter the aggregated rows for just those with the max, then UNWIND them back into rows and return them.
MATCH (n:student)
WITH n.name as name, count(*) as times
WITH collect({name:name, times:times}) as rows, max(times) as max
UNWIND [row in rows WHERE row.times = max] as row
RETURN row.name as name, row.times as times
Upvotes: 1