Cypher:使用 CALL 子查询实现 EXISTS 子查询功能

Cypher: implement EXISTS sub query functionality with a CALL sub query

假设我有一个匹配项:MATCH (from: FromLabel)-[:REL_LABEL]-(to: ToLabel)

我希望能够根据是否存在通往特定 OtherLabel 节点的路径以及一些其他条件和可能的匹配或聚合来过滤掉 from 节点。类似的东西:

MATCH (from: FromLabel)-[:REL_LABEL]-(to: ToLabel)
WHERE EXISTS {
MATCH (from: FromLabel)-[:OTHER_REL_LABEL]-(other: OtherLabel)
WHERE other.some_prop = 'value'
WITH from, SUM(other.another_prop) as aggregation_by_from
// ** here goes some more possible match where based on other
}

但我根本做不到,因为 EXISTS{...} 只需要一个 MATCH(...) WHERE(...) 子句(当然还有可选的 EXISTS 嵌套)

问题如何使用 CALL 子查询实现更丰富的 Exists 功能?

最终想通了:

通过两个嵌套的 CALL 子查询,我可以为每个 from 节点模拟布尔谓词的功能。请注意,内部 CALL 表达式使用 UNION,因此它总是 returns FALSE。当内部 MATCH...WHERE...<ANYTHING> CALL 子查询也被评估并执行 RETURN TRUE AS predicate LIMIT 1 - 它将 return 给定 from 节点的两个 TRUE, FALSE 行。

因此,我们需要外部 CALL 的唯一目的是筛选出最合适的解决方案:

  1. 如果只对 RETURN FALSE AS predicate LIMIT 1 进行了评估,那么外部 RETURN predicate LIMIT 1 就什么都没有了。
  2. 如果 RETURN TRUE AS predicate LIMIT 1 也被评估 - 那么外部 RETURN predicate LIMIT 1 将删除 FALSE 行。
MATCH (from: FromLabel)-[:REL_LABEL]-(to: ToLabel)
CALL {
    WITH from
    CALL {
        WITH from
        MATCH (from: FromLabel)-[:OTHER_REL_LABEL]-(other: OtherLabel)
        WHERE // any following conditions you'd like or other expressions
        RETURN TRUE AS predicate LIMIT 1
     UNION
        RETURN FALSE AS predicate LIMIT 1
    }
    RETURN predicate LIMIT 1

}
RETURN from