Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return top n results for each query in Neo4j

Tags:

neo4j

cypher

I've been trying to writhe the following task in cypher query but I am not getting the right results. Other stackoverflow questions discuss limit or collect but I do not think that is enough to do the following task.

Task: I have (p:Product) nodes and between two product nodes there is a relationship called "BOUGHT_TOGETHER". That is

(p:Product)-[b:BOUGHT_TOGETHER]-(q:Product)

And the relationship b has a property called "size" which contains some number. I want to return top 3 results for each product relationship which is ordered by the size. For instance, the query result should look like the following.

+------------------------+
| p.id  | q.id | b.size      |
+------------------------+
   1      2      10
   1      3       8
   1      5       7
   2      21      34
   2      17      20
   2      35      15
   3      5       49
   3      333     30
   3       65      5
   .       .       .
   .       .       .
   .       .       .

Can someone show me how to write a cypher query in order to achieve the desired results? Thank you!

like image 634
user4279562 Avatar asked Dec 10 '22 20:12

user4279562


1 Answers

Another solution is to first order the relationships, pipe them in a collection and UNWIND only the 3 first results of the collection :

MATCH (p:Product)-[r:BOUGHT_TOGETHER]->(:Product)
WITH p, r
ORDER BY r.size DESC 
WITH p, collect(r) AS bts 
UNWIND bts[0..3] AS r
RETURN p.uuid as pid, endNode(r).uuid as qid, r.size as size

Test console here : http://console.neo4j.org/r/r88ijn

NB: After re-reading jjaderberg's answer this is a bit similar, just I think more readable. Why I voted for his answer.

like image 165
Christophe Willemsen Avatar answered Jan 17 '23 12:01

Christophe Willemsen