如何使两个Cypher可选匹配不产生重复结果?

huangapple go评论118阅读模式
英文:

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

如果每个LIKEDDISLIKED关系的起始节点始终是一个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.

huangapple
  • 本文由 发表于 2023年3月12日 14:20:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定