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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With