1

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

1 回答 1

0

这正是可选关系的用例。如果没有?:KNOWS要匹配的选项,您对 cypher 说:“我只想将那些与另一个人有 :KNOWS 关系的人匹配。将他们连同关系的数量一起返回。” 根据您要求的 MATCH,这会正确排除那些没有 :KNOWS 关系的人。

通过 将关系添加为可选?:KNOWS,您是在询问 cypher:“请给我所有人并使用 :KNOWS 关系将他们与其他人匹配,如果他们有的话。返回所有人并计算他们的朋友。”

你能解释一下为什么在这种情况下你不能使用可选关系来进行匹配,因为在我看来它是完成这项工作的确切工具吗?

于 2013-09-16T16:34:30.583 回答