cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Any way to create when nothing to connect to?

geronimo4j
Graph Buddy

Hi I'm currently looking at connecting a new node to an existing node, but if there is no existing node then I want to create that too. Is there any way to do that?

Essentially I have:

Post->Link

And I want links to be nodes, so if there is a new Post sharing a Link that has been seen before, I'm connecting that new Post to that existing Link. Is there a clever way to write a mutation to say "Connect Post to Link, unless Link doesn't exist yet, then create Link and connect them?"

1 REPLY 1

Hi Dan,

The MERGE keyword can be used to MATCH if exists, or CREATE if it does not exists.
So MERGE (a:Foo {uuid: "ABC123"})-[:MY_REL]->(b:Bar {uuid: "123ABC"})
will always result in node (a) being linked to node (b), and if either of those nodes did not yet exist, they would be created.
and you can add this to set the properties if the node did not exist:
ON CREATE SET b.foo = "bar", b.bar = "foo"

For your use case this would be the best way to do it:

MATCH (a:Foo {uuid: "ABC123"})
MERGE (a)-[:MY_REL]->(b:Bar {uuid: "123ABC"})
ON CREATE SET b.foo = "bar", b.bar = "foo"

That way if it fails to MATCH (a) then it wont create (b). But if (a) is found, (b) will always be found if it exists, and created if it doesnt and then linked in either case.