Neo4j Cypher查询:订单收集,先取n个元素

时间:2013-10-17 09:23:52

标签: neo4j cypher

我在为这种社交网络类型的应用程序编写Cypher查询时遇到问题。它涉及添加帖子的用户(实际上是带有描述的图像),用户可以查看。

在Cypher中,图模型如下: (user)-[:WROTE_REVIEW]->(review)-[:EVALUATES]->(post)

我尝试撰写的查询应返回特定用户已审核过的所有帖子,以及有关帖子评论的一般信息。

这包括:

  1. (帖子的ID)
  2. 帖子的图片
  3. 帖子的描述
  4. 此帖子的评论总数
  5. 此帖子的评论者总数
  6. 此帖子的最后6位评论者的头像,按照评论日期排序,降序
  7. 我想我已经成功完成了前五项,但第6项给了我麻烦。下面的查询给了我所有的头像,而我只需要最后的6个。

    START user=node(2515)
    MATCH (user)-[:WROTE_REVIEW]->()-[:EVALUATES]->(post)
    WITH distinct post
    MATCH (review)-[:EVALUATES]->(post)
    WITH post, count(review) as reviews
    MATCH (reviewer)-[:WROTE_REVIEW]->()-[:EVALUATES]->(post)
    WITH post, reviews, count(distinct reviewer) as reviewers, collect(distinct reviewer.Avatar) as avatars
    ORDER BY post.CreationTime DESC
    RETURN post.Id, post.Image, post.Description, reviews, reviewers, avatars;
    

    有人可以告诉我如何按审核日期(即review.CreationTime)降序订购头像,并采取前六项吗?

    谢谢!

2 个答案:

答案 0 :(得分:4)

您可以先对行进行排序,然后选择审阅者集合的前6位,而不是对集合进行排序。所以将最后一场比赛更改为类似的内容,

MATCH (reviewer)-[:WROTE_REVIEW]->(review)-[:EVALUATES]->(post)
With distinct post, reviewer, review
ORDER BY post.CreationTime DESC, review.CreationTime DESC
Return post, count(reviewer) as reviewers, collect(reviewer.Avatar)[0..5] as avatars

使用索引(例如[0..5])访问集合需要2.0 M5的版本。

答案 1 :(得分:2)

Neo4j 2.0中的集合切片是关键。我不得不在我的结果中加入一些distinct条款,因为一些重复项目即将出现。这就是我最终的结果:

START user=node(2515)
MATCH (user)-[:WROTE_REVIEW]->()-[:EVALUATES]->(post)
WITH distinct post
MATCH (review)-[:EVALUATES]->(post)
WITH post, count(review) as reviews
MATCH (reviewer)-[:WROTE_REVIEW]->(review)-[:EVALUATES]->(post)
WITH distinct post, reviewer, review, reviews
ORDER BY review.CreationTime, post.CreationTime DESC
RETURN post.Id AS postId, post.Image AS postImage, post.Description AS postDescription, reviews AS Reviews, count(distinct reviewer) AS Reviewers, collect(distinct reviewer.Avatar)[0..5] AS Avatars