START n =节点(*)和MATCH(n)之间的差异

时间:2014-02-07 17:25:47

标签: neo4j

在Neo4j 2.0中这个查询:

MATCH (n) WHERE n.username = 'blevine' 
OPTIONAL MATCH n-[:Person]->person
OPTIONAL MATCH n-[:UserLink]->role
RETURN n AS user,person,collect(role) AS roles

会返回与此查询不同的结果:

START n = node(*) WHERE n.username = 'blevine' 
OPTIONAL MATCH n-[:Person]->person
OPTIONAL MATCH n-[:UserLink]->role
RETURN n AS user,person,collect(role) AS roles

第一个查询按预期工作,返回“blevine”的单个节点以及OPTIONAL MATCH子句中提到的相关节点。第二个查询返回更多甚至没有用户名属性的节点。我意识到不建议启动n = node(*),并且在2.0中甚至不需要START。但第二种形式(OPTIONAL MATCH替换为关系类型上的问号)在2.0之前工作。在第二种形式中,为什么'n'不会被第一个WHERE子句约束到单个'blevine'节点?

1 个答案:

答案 0 :(得分:2)

要按预期运行第二个查询,您只需添加WITH n即可。在您的查询中,您需要过滤结果并将其传递给可选匹配,这将使用WITH

完成
START n = node(*) WHERE n.username = 'blevine' 
WITH n
OPTIONAL MATCH n-[:Person]->person
OPTIONAL MATCH n-[:UserLink]->role
RETURN n AS user,person,collect(role) AS roles

来自文档

WHERE defines the MATCH patterns in more detail. The predicates are part of the 
pattern description, not a filter applied after the matching is done. 
This means that WHERE should always be put together with the MATCH clause it belongs to.

当你开始n = node(*),其中n.name =“xyz”你需​​要将结果明确地传递给你的下一个可选匹配。但是当你做MATCH(n)WHERE n.name =“xyz”时,这会特别告诉图形开始研究的节点。

修改

这是事情。文档说可选匹配返回null如果找不到模式,那么在第一种情况下,它包括n.username属性为null的所有结果或n的情况甚至没有OPTIONAL MATCH模式中建议的关系。因此,当您执行WITH n时,会明确告知图表仅使用n。

摘自文档(链接:here

OPTIONAL MATCH matches patterns against your graph database, just like MATCH does. 
The difference is that if no matches are found, OPTIONAL MATCH will use NULLs for 
missing parts of the pattern. OPTIONAL MATCH could be considered the Cypher 
equivalent of the outer join in SQL.


Either the whole pattern is matched, or nothing is matched. Remember that 
WHERE is part of the pattern description, and the predicates will be 
considered while looking for matches, not after. This matters especially
in the case of multiple (OPTIONAL) MATCH clauses, where it is crucial to 
put WHERE together with the MATCH it belongs to.

还有一些关于WHERE子句行为的注意事项:here

摘录:

WHERE is not a clause in it’s own right — rather, it’s part of MATCH, 
OPTIONAL MATCH, START and WITH.

In the case of WITH and START, WHERE simply filters the results.

For MATCH and OPTIONAL MATCH on the other hand, WHERE adds constraints
to the patterns described. It should not be seen as a filter after the
matching is finished.