简体   繁体   English

Neo4J cypher 可选匹配如何工作?

[英]How does Neo4J cypher OPTIONAL MATCH works?

I ran into a problem today understanding OPTIONAL MATCH clause in cypher.我今天在理解 cypher 中的 OPTIONAL MATCH 子句时遇到了问题。 Let's consider this simple case:让我们考虑这个简单的案例:

CREATE (:a {type:"group"})-[:a_rel]->(:a {type: "app"})-[:b_rel]->(:b);

This creates 2 "a" node with different type attribute, plus one "b" node.这将创建 2 个具有不同类型属性的“a”节点,以及一个“b”节点。 All of them are in a simple path a-->a-->b它们都在一个简单的路径中 a-->a-->b

Then, I'm trying to match the "a" node having "group" type, connected to the other "a" node, optionaly connected to the "b" node.然后,我试图匹配具有“组”类型的“a”节点,连接到另一个“a”节点,可选地连接到“b”节点。

So, if I run the following query, I expect it to return nothing:因此,如果我运行以下查询,我希望它不会返回任何内容:

MATCH(x:a)-->(y:a) 
where x.type = "group" 
OPTIONAL MATCH (y)-->(z:b) 
where z IS NULL 
return y

but it always return the second "a" node of the path, using IS NULL or IS NOT NULL on the where clause.但它总是返回路径的第二个“a”节点,在 where 子句中使用 IS NULL 或 IS NOT NULL。

Could you please explain me what I do not understand here.你能解释一下我在这里不明白的地方吗? In my real model, the second "a" node can be connected or not to the "b" node.在我真正的 model 中,第二个“a”节点可以连接或不连接到“b”节点。 I would like to retrieve all the one that are not connected to any "b" node.我想检索所有未连接到任何“b”节点的节点。

Thanks a lot for your help非常感谢你的帮助

Rémi雷米

What OPTIONAL MATCH does is, it tries to find out patterns in the graph.If matching pattern is found that Node is returned, else it is replaced with NULL.I hope this will clear the confusion caused. OPTIONAL MATCH 所做的是,它试图找出图中的模式。如果找到匹配模式,则返回 Node,否则将其替换为 NULL。我希望这会消除造成的混乱。

As long as the MATCH clause finds a match, the query will always return y .只要MATCH子句找到匹配项,查询将始终返回y

This is because the OPTIONAL MATCH does not need to match anything in order for the query to proceed.这是因为OPTIONAL MATCH不需要匹配任何内容来进行查询。 That is why it is "OPTIONAL".这就是为什么它是“可选的”。

This is one way to do what you intended:这是做你想做的事情的一种方法:

MATCH (x:a)-->(y:a)
WHERE x.type = "group" AND NOT (y)-->(:b)
RETURN y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM