在 Neo4j 中为每个查询返回前 n 个结果 [英] return top n results for each query in Neo4j

查看:36
本文介绍了在 Neo4j 中为每个查询返回前 n 个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在密码查询中执行以下任务,但没有得到正确的结果.其他 stackoverflow 问题讨论了限制或收集,但我认为这不足以完成以下任务.

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.

任务:我有 (p:Product) 节点,并且在两个产品节点之间有一个名为BOUGHT_TOGETHER"的关系.那是

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)

关系 b 有一个名为size"的属性,其中包含一些数字.我想返回按大小排序的每个产品关系的前 3 个结果.例如,查询结果应如下所示.

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!

推荐答案

另一种解决方案是先对关系进行排序,将它们放入一个集合中,然后仅 UNWIND 集合的前 3 个结果:

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

在这里测试控制台:http://console.neo4j.org/r/r88ijn

注意:在重新阅读 jjaderberg 的回答后,这有点相似,只是我认为更具可读性.为什么我投票支持他的答案.

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

这篇关于在 Neo4j 中为每个查询返回前 n 个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆