在查询中计算每个帖子的4条最新评论

时间:2017-01-31 18:27:43

标签: neo4j

我有以下查询来获取具有计算数量的喜欢的帖子以及创建帖子的计算用户:

MATCH (post:Post)
WITH post
ORDER BY post.createdAt DESC
MATCH (user:User)-[:CREATED]->(post)
RETURN post, user.username AS createdBy,
       size((post)<-[:LIKES]-(:User)) AS likes
SKIP {skip}
LIMIT {limit}

我需要的是为每个帖子计算最后4个创建的评论。如果有0条评论,我想返回空数组,并且帖子也有可能少于4条评论,所以只会显示这些评论的数组。

我需要这样的smth(我添加了虚构的查询):

MATCH (post:Post)
WITH post
ORDER BY post.createdAt DESC
MATCH (user:User)-[:CREATED]->(post)
[MATCH (comment:Comment)-[:BELONGS_TO]->(post:Post) ORDER BY comment.timestamp ASC]
RETURN post, user.username AS createdBy,
       size((post)<-[:LIKES]-(:User)) AS likes,
       comment AS comments
SKIP {skip}
LIMIT {limit}

1 个答案:

答案 0 :(得分:2)

这可能会做你想要的:

MATCH (user:User)-[:CREATED]->(post:Post)
WITH user, post
ORDER BY post.createdAt DESC
OPTIONAL MATCH (post)<-[:BELONGS_TO]-(comment:Comment)
WITH user, post, comment
ORDER BY comment.timestamp DESC
RETURN post, user.username AS createdBy,
       size((post)<-[:LIKES]-(:User)) AS likes,
       COLLECT(comment)[0..4] AS latestComments
SKIP {skip}
LIMIT {limit}

它返回帖子(按降序排列),每个帖子返回创建者的姓名,喜欢的数量以及最后4个评论的集合(最多)。它使用OPTIONAL MATCH来确保它返回根本没有评论的帖子。