简体   繁体   中英

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.

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):

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. Other than breaking it up into multiple queries, is there a way to accomplish this?

I think you need to hack it with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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