是的,这是可能的。我们只需要在查询中尽早移动LIMIT来限制帖子,并且只有在限制后才能开始执行这些可选匹配。
您可能还需要阅读WITH子句(用于划分查询的一部分)和COLLECT()函数,以将行收集到单个列表中。
我们还可以使用0..1
的可变长度关系来改进初始匹配,以便始终将起始节点包含在与u1
的匹配中。
在某些情况下,我们也可以使用pattern comprehension而不是可选匹配来执行匹配并收集列表中的结果。
MATCH (post:Post)<-[:POSTED]-(poster:User)-[:FRIENDS_WITH*0..1]-(:User {id: {id}})
WITH post, poster
ORDER BY post.timestamp DESC LIMIT 10
WITH post, poster, [(u:User)-[:LIKES]->(post) | u] as usersWhoLiked
// each post, poster, and collection of liking users on a row
OPTIONAL MATCH (commenter:User)-[:COMMENTED]->(comment:Comment)<-[:HAS_COMMENT]-(post)
// now for each comment on a row, collect users who liked the comment
WITH post, poster, usersWhoLiked, comment, commenter, [(u:User)-[:LIKES]->(comment) | u] as commentLikers
RETURN post, poster, usersWhoLiked, comment, commenter, commentLikers
这会给你每个帖子的评论(和评论者,以及那些喜欢评论者的列表)。帖子,海报和usersWhoLiked列表将与每个相关评论一起显示。
如果你想收集的意见太多,所以只会有每行一个职位,那么需要改变的查询结束。你会需要更换RETURN行:
...
// now for each post on a row, collect the comments, commenter, and likers per comment
WITH post, poster, usersWhoLiked, collect(comment {.*, commenter, commentLikers}) as comments
RETURN post, poster, usersWhoLiked, comments
这是使用map projection输出,为每个评论,地图注释的属性,以及添加了评论者的地图,并且用户的列表谁喜欢评论。
谢谢!我不知道你可以在查询的其余部分之前使用limit子句。 – singwukgwu