简体   繁体   English

Neo4j和Cypher - 可选匹配的奇怪行为

[英]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 . 我想写一个删除所有foobar实例的查询,问题是有时fooParent不存在,并且有时单个foo不会连接到任何bar Because of those conditions I decided to match fooParent and bar nodes in OPTIONAL MATCH query. 由于这些条件,我决定在OPTIONAL MATCH查询中匹配fooParentbar节点。

Now in first graph (where fooParent and bar nodes are present) everything I want is matched ( foo1 and all bar nodes) using 现在在第一个图形中(其中存在fooParentbar节点)我想要的所有内容都匹配( 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条款

  • completely matches, in which case it will return the matching rows with every identifier bound, or 完全匹配,在这种情况下,它将返回匹配的行与每个标识符绑定,或
  • it will not completely match, in which case it will return a single row with any unbound identifiers set to 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.

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