问题:如何在不使用可选关系的情况下计算单个 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 |
+---------------------------+