PPSATO
PPSATO

Reputation: 115

Getting the top 10 values of a property in Neo4j cypher

I have a node N1 on my graph. This node has multiple properties. I am interested in properties P1 and P2. For each property P1, there can be multiple "rows" of P2. I want to pull out the top 10 P2's for each P1 in node N1. I have tried the following approach:

match (m:N1)
where m.P1 is not null

with m
match(n:N1{P1:m.P1})
where n.P2 is not null
return 
m.P1 as P1_test, n.P2 as P2_test, count(*) as testCount
order by testCount desc
limit 10

The above does not give me the right values. I have also tried the following:

match (n:N1) where n.P1 is not null
with n.P1 as P1_test
match (m:N1{P1:P1_test})
where m.P2 is not null
return
m.P1,
collect (m.P2) as P2_test

This doesn't work and I am not able to add the count in here to limit to the top 10 results of the query. I'm not sure if I am missing something basic here. Any help in the right direction would be very much appreciated.

Upvotes: 1

Views: 462

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12684

  • You can do one match query to check if P1 and P2 are not null.
  • Then sort the result by P1 and count of P2 in descending order.
  • Collect P2 and its count then get the top 10 rows
  • Unwind is like a for loop
  • Lastly, return P1 and P2

In the future, please also give us sample data to work on. Thanks.

match (n:N1) where n.P1 is not null and n.P2 is not null
with n.P1 as P1_test, n.P2 as P2_test, count(n.P2) as cnt order by P1_test, cnt desc
with P1_test,  collect({p2: P2_test, cnt:cnt})[..10] as p2_list
unwind p2_list as c
with P1_test, c.p2 as P2_test
return P1_test, P2_test

Upvotes: 1

Graphileon
Graphileon

Reputation: 5385

After the WHERE, you could do this :

WITH
m.P1 AS P1_test, n.P2 AS P2_test, count(*) AS testCount
ORDER BY testCount DESC
WITH P1_test, collect(P2_test) AS P2s
RETURN P1_test, P2s[..10] AS top10

Upvotes: 0

Related Questions