[英]Neo4j and Cypher - strange behaviour of OPTIONAL MATCH
Today I was writing DELETE query for some parts of my graph but I am having some problems with OPTIONAL MATCH
. 今天我正在为我的图形的某些部分编写DELETE查询但是我在使用OPTIONAL MATCH
时遇到了一些问题。
Firstly here are example graphs: 首先是示例图:
http://console.neo4j.org/r/micnvv http://console.neo4j.org/r/micnvv
and 和
http://console.neo4j.org/?id=og6d9s http://console.neo4j.org/?id=og6d9s
I wanted to write a query that deletes all foo
and bar
instances, problem is that sometimes fooParent
will not exists and also there are cases when single foo
will not be connected to any bar
. 我想写一个删除所有foo
和bar
实例的查询,问题是有时fooParent
不存在,并且有时单个foo
不会连接到任何bar
。 Because of those conditions I decided to match fooParent
and bar
nodes in OPTIONAL MATCH
query. 由于这些条件,我决定在OPTIONAL MATCH
查询中匹配fooParent
和bar
节点。
Now in first graph (where fooParent
and bar
nodes are present) everything I want is matched ( foo1
and all bar
nodes) using 现在在第一个图形中(其中存在fooParent
和bar
节点)我想要的所有内容都匹配( foo1
和所有bar
节点)
MATCH (foo:Foo { customId: '1' })
OPTIONAL MATCH foo -[rel]-> bar,(fooParent: FooParent)-[fooParentRel]-> foo
RETURN foo, bar
In the second graph I have a situation where fooParent
for given foo
does not exists and the same query does not match bar
nodes - only foo
is matched as you can see. 在第二个图中我有一种情况,其中给定foo
fooParent
不存在,并且相同的查询与bar
节点不匹配 - 只有foo
匹配,如您所见。
I was thinking that OPTIONAL MATCH
is the way to go in case such as mine but it does not seem to be working. 我认为OPTIONAL MATCH
是我的方式,例如我的,但似乎没有用。
Well yes, because an OPTIONAL MATCH
clause either 是的,因为一个OPTIONAL MATCH
条款
null
. 它不会完全匹配,在这种情况下,它将返回一行,其中任何未绑定标识符设置为null
。 In this case, your OPTIONAL MATCH
contains two parts: it tries to match Foo
nodes that have outgoing relationships (to some bar) and incoming relationships to a FooParent
. 在这种情况下,您的OPTIONAL MATCH
包含两部分:它尝试匹配具有传出关系(对某些条)的Foo
节点以及与FooParent
传入关系。
The solution is to split up the OPTIONAL MATCH
: 解决方案是拆分OPTIONAL MATCH
:
MATCH (foo:Foo { customId: '1' })
OPTIONAL MATCH foo -[rel]-> bar
OPTIONAL MATCH (fooParent: FooParent)-[fooParentRel]-> foo
RETURN foo, bar
In the second graph, by running two distinct optional match functions the following query will work 在第二个图中,通过运行两个不同的可选匹配函数,以下查询将起作用
MATCH (foo:Foo { customId: '1' })
OPTIONAL
MATCH (foo)-[r]->(bar)
OPTIONAL
MATCH (fooParent:fooParent)-[fooParentRel]->(foo2)
RETURN foo, bar, foo2
Cheers, 干杯,
Chris 克里斯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.