Cypher 查询不返回不存在的关系

Cypher Query not returning nonexistent relationships

我有一个图形数据库,其中有用户和兴趣节点,它们通过 IS_INTERESTED 关系连接。我想找到用户未选择的兴趣。我写了这个查询,但它不起作用

OPTIONAL MATCH (u:User{userId : 1})-[r:IS_INTERESTED] -(i:Interest)
WHERE r is NULL
Return i.name as interest

根据 SO 上类似问题的答案(如 this 一个),上面的查询应该是 work.However,在这种情况下它 returns 为空。但是当 运行 执行以下查询时,它会按预期工作:

MATCH (u:User{userId : 1}), (i:Interest)
WHERE NOT (u) -[:IS_INTERESTED] -(i)
return i.name as interest

我不想运行上述查询的原因是因为Neo4j给出警告:

This query builds a cartesian product between disconnected patterns.

If a part of a query contains multiple disconnected patterns, this will build a cartesian product between all those parts. This may produce a large amount of data and slow down query processing. While occasionally intended, it may often be possible to reformulate the query that avoids the use of this cross product, perhaps by adding a relationship between the different parts or by using OPTIONAL MATCH (identifier is: (i))

我在使用 OPTIONAL MATCH 查找不存在的关系的第一个查询中做错了什么?

在 OPTIONAL MATCH 之后直接 拉入 评估的 WHERE。

如果你想 post-filter 你必须在两者之间使用 WITH。

MATCH (u:User{userId : 1})
OPTIONAL MATCH (u)-[r:IS_INTERESTED] -(i:Interest)
WITH r,i
WHERE r is NULL
Return i.name as interest

如果您的 OPTIONAL MATCH 查询未找到匹配项,则 ri 都必须是 NULL。毕竟,既然没有关系,就没有办法得到它指向的节点。

1) MATCH 正在寻找整个模式,如果找不到完整的模式 - 不会 return 任何东西。

2) 我认为这个查询会有效:

// Take all user interests
MATCH (u:User{userId: 1})-[r:IS_INTERESTED]-(i:Interest)
    WITH collect(i) as interests
    // Check what interests are not included
    MATCH (ni:Interest) WHERE NOT ni IN interests
RETURN ni.name