简体   繁体   English

在Neo4j 2.0中将可选节点与Cypher查询链接

[英]Linking Optional Nodes with Cypher Query in Neo4j 2.0

I'm trying to figure out the correct way to attach newly created nodes to additional nodes that may or may not exist. 我正在试图找出将新创建的节点附加到可能存在或可能不存在的其他节点的正确方法。 Basically, CREATE A and if B exists, LINK B to A and RETURN A. If B doesn't exist just RETURN A. 基本上,CREATE A和如果B存在,LINK B到A和RETURN A.如果B不存在,只返回A.

This is my Cypher query (the extra WITH clauses are because this is part of a larger query and I'm trying to make sure this sample code works the same way): 这是我的Cypher查询(额外的WITH子句是因为这是一个更大的查询的一部分,我正在尝试确保此示例代码以相同的方式工作):

CREATE (a:A { foo: "bar" })
WITH a

OPTIONAL MATCH (b:B)
WHERE a.foo = b.foo
CREATE UNIQUE b-[:LINK]->a
WITH a

RETURN a

This doesn't work since the CREATE UNIQUE fails since b is NULL. 这不起作用,因为CREATE UNIQUE失败,因为b为NULL。 Other than breaking it up into multiple queries, is there a way to accomplish this? 除了将其分解为多个查询之外,有没有办法实现这一目标?

I think you need to hack it with foreach... 我认为你需要用foreach来破解它...

CREATE (a:A { foo: "bar" })
WITH a

OPTIONAL MATCH (b:B)
WHERE a.foo = b.foo
WITH a, collect(b) as bs
FOREACH(b in bs | CREATE UNIQUE b-[:LINK]->a)
WITH a

RETURN a

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

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