英文:
How to make two Cypher optional matches not multiply results?
问题
OPTIONAL MATCH (:User)-[l:LIKED]->(:User {username: $username})
OPTIONAL MATCH (:User)-[d:DISLIKED]->(:User {username: $username})
RETURN count(l), count(d)
英文:
OPTIONAL MATCH (:User)-[l:LIKED]->(:User {username: $username})
OPTIONAL MATCH (:User)-[d:DISLIKED]->(:User {username: $username})
RETURN count(l),count(d)
I have this Cypher query to return the count of 2 types of relationships. Currently there are 7 :LIKED edges and 5 :DISLIKED edges running into the given username, but when I run this I get both counts as 35. How can I change it to not be multiplied?
答案1
得分: 1
如果每个LIKED
和DISLIKED
关系的起始节点始终是一个User
,那么我们可以使用一种路径模式,让起始节点保持不明确。在这种情况下,获取计数的最有效方式如下(因为它会导致Cypher规划器使用getDegree
操作计算关系的数量,而无需访问数据库):
OPTIONAL MATCH (u:User {username: $username})
RETURN
SIZE([()-[:LIKED]->(u)|1]) AS count_l,
SIZE([()-[:DISLIKED]->(u)|1]) AS count_d
此答案到另一个问题提供了更多细节。
英文:
If the start node of every LIKED
and DISLIKED
relationship is always a User
, then we can use a path pattern that leaves the start node unspecific. In this case, the most efficient way to get the counts is as follows (since it causes the Cypher planner to count relationships using the getDegree
operation, which does not need to hit the DB):
OPTIONAL MATCH (u:User {username: $username})
RETURN
SIZE([()-[:LIKED]->(u)|1]) AS count_l,
SIZE([()-[:DISLIKED]->(u)|1]) AS count_d
This answer to another question provides more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论