问题:如何计算单个Cypher查询中两个独立模式的出现而不使用可选关系?
示例:为社交网络中的每个人计算他们拥有多少朋友以及他们制作了多少帖子。
通过可选关系,它很容易......
统计人的朋友:
MATCH (person:PERSON)
WITH person
MATCH (person)-[?:KNOWS]-(friend:PERSON)
RETURN person.firstName AS name, count(friend) AS friends
+----------------------+
| name | friends |
+----------------------+
| "alex" | 3 |
| "aiya" | 1 |
| "jacob" | 1 |
| "peter" | 1 |
| "stranger" | 0 |
+----------------------+
统计人员职位:
MATCH (person:PERSON)
WITH person
MATCH (person)<-[?:HAS_CREATOR]-(post:POST)
RETURN person.firstName AS name, count(post) AS posts
+--------------------+
| name | posts |
+--------------------+
| "alex" | 0 |
| "aiya" | 3 |
| "jacob" | 3 |
| "peter" | 1 |
| "stranger" | 2 |
+--------------------+
统计人物的朋友和帖子:
MATCH (person:PERSON)
WITH person
MATCH (person)-[?:KNOWS]-(friend:PERSON)
WITH person, count(friend) AS friends
MATCH (person)<-[?:HAS_CREATOR]-(post:POST)
RETURN person.firstName AS name, friends, count(post) AS posts
+------------------------------+
| name | friends | posts |
+------------------------------+
| "peter" | 1 | 1 |
| "aiya" | 1 | 3 |
| "alex" | 3 | 0 |
| "stranger" | 0 | 2 |
| "jacob" | 1 | 3 |
+------------------------------+
但是,如果没有可选关系,查询结果将排除在两个MATCH
子句中任何一个中具有零计数结果的所有节点:
MATCH (person:PERSON)-[:KNOWS]-(friend:PERSON)
WITH person, count(friend) AS friends
MATCH (person)<-[:HAS_CREATOR]-(post:POST)
RETURN person.firstName AS name, friends, count(post) AS posts
+---------------------------+
| name | friends | posts |
+---------------------------+
| "peter" | 1 | 1 |
| "aiya" | 1 | 3 |
| "jacob" | 1 | 3 |
+---------------------------+
仅供参考,期望的结果是:
+---------------------------+
| name | friends | posts |
+---------------------------+
| "alex" | 3 | 0 |
| "peter" | 1 | 1 |
| "aiya" | 1 | 3 |
| "jacob" | 1 | 3 |
+---------------------------+
答案 0 :(得分:0)
这正是可选关系的用例。如果没有与之匹配的可选?:KNOWS
,你就会说“我想只匹配那些与另一个人有:知道关系的人。将它们与关系数量一起归还。”而且,基于您要求的MATCH,正确排除那些没有:知道关系的人。
通过?:KNOWS
将关系添加为可选关系,您要求密码:“请让我所有人并将其与使用:KNOWS关系的其他人匹配,如果他们有一个。返回所有人并计算他们的朋友。“
在这种情况下,你能解释为什么你不能使用可选关系进行匹配,因为在我看来它是这项工作的确切工具吗?