我有以下查询:
MATCH (user:User)-[:CREATED]->(post:Post)
WITH user, post
ORDER BY post.createdAt DESC
OPTIONAL MATCH (post)<-[:BELONGS_TO]-(comment:Comment)<-[:COMMENTED]-(:User)
WITH user, post, liked, comment
ORDER BY comment.timestamp DESC
WITH user, post, liked, COLLECT(comment)[0..4] AS comments
RETURN post,
{ username: user.username,
firstName: user.firstName,
lastName: user.lastName,
profilePicture: user.profilePicture
} AS createdBy,
size((post)<-[:LIKES]-(:User)) AS likes,
liked,
comments
SKIP {skip}
LIMIT {limit}
查询获取帖子列表并计算其他内容,例如: 获得发表评论,获得创建帖子的用户,获得喜欢的总数。
我还需要计算我是否喜欢这个帖子,这会导致:userLiked(true | false)。
我想的是:
OPTIONAL MATCH (post)<-[userLiked:LIKES]-(:User {uuid: {userUUID}})
答案 0 :(得分:1)
如果你只需要一个真/假,那么EXISTS()是一个更好的选择。
您还可以通过将查询结束时的SKIP和LIMIT移动到ORDER BY后创建帖子来提高性能。
如果你正在使用Neo4j 3.1.x或更高版本,你可以使用地图投影使其更容易在createdBy地图上返回你需要的字段。
以下是包含所有这些内容的查询:
MATCH (user:User)-[:CREATED]->(post:Post)
WITH user, post
ORDER BY post.createdAt DESC
OPTIONAL MATCH (post)<-[:BELONGS_TO]-(comment:Comment)<-[:COMMENTED]-(:User)
WITH user, post, comment
ORDER BY comment.timestamp DESC
WITH user, post, COLLECT(comment)[..4] AS comments
SKIP {skip} LIMIT {limit}
RETURN post,
user { .username, .firstName, .lastName, .profilePicture } AS createdBy,
size((post)<-[:LIKES]-(:User)) AS likes,
exists((post)<-[:LIKES]-(:User{uuid: {userUUID}})) AS userLiked,
comments