获取嵌套查询中帖子的评论回复

时间:2016-04-09 04:55:48

标签: neo4j cypher

我正在撰写查询以获取您朋友的所有帖子,每篇帖子的评论以及每条评论的回复:

MATCH (:User {email:{my_email}})-[:Friends]->(other_user:User)-[:Published]->(post:Post)
    OPTIONAL MATCH (commenters:User)-[:Published]->(comments:Comment)-[:Comments]->post
    OPTIONAL MATCH (repliers:User)-[:Published]->(reply:Reply)-[:Replied]->comments
    WITH post, other_user, comments, reply
    ORDER BY comments.timestamp DESC, reply.timestamp DESC
    RETURN post AS posts, other_user AS other, Collect(comments) AS comments, Collect(reply) as replies
    ORDER BY post.timestamp DESC LIMIT 20

我可以收到帖子的所有帖子和评论,但无法收到评论的回复

我们如何执行这样的查询?

1 个答案:

答案 0 :(得分:1)

我想出了如何查询

这是正确的查询:

  MATCH (:User {email:{my_email}})-[:Friends]->(User)-[:Published]->(post:Post)
  OPTIONAL MATCH (commenters:User)-[:Published]->(comment:Comment)-[:Commented]->post
  OPTIONAL MATCH (repliers:User)-[:Published]->(reply:Reply)-[:Replied]->comment
  WITH post, comment, reply
  ORDER BY reply.timestamp ASC
  WITH post, comment, Collect(reply) as replies
  ORDER BY comment.timestamp ASC
  WITH post, Collect({comment: comment, replies: replies}) as comments
  ORDER BY post.timestamp DESC
  RETURN Collect({post:post, comments:comments}) as posts

查询说明:

  1. 我们收到所有朋友的帖子
  2. 某些Post可能还没有评论,因此我们在OPTIONAL MATCH上使用Comment
  3. 某些Comment可能没有回复,因此我们在OPTIONAL MATCH上也使用了Reply
  4. ORDER BY ASC订单中的回复..从最旧到最新
  5. Collect所有回复
  6. 然后ORDER BY ASC中的评论也是从最旧到最新的
  7. 然后Collect每个人Comment及其相关回复
  8. ORDER BY DESC订单中的帖子..从最新到最旧
  9. 然后Collect每个人Post及其相关评论