0
votes

I'm trying to find two nodes in my database and then create a relationship between them. I'm using the neo4j python package. Current code looks like so:

from neo4j import GraphDatabase
graphDB_Driver  = GraphDatabase.driver(...) 
db = graphDB_Driver.session()

db.run("MERGE (a:Person {name:'Homer'})")
db.run("MERGE (a:Person {name:'Marge'})")

This part works fine.

Now how do I retrieve the two nodes above and create a relationship between them?

db.run("MERGE (:Person {name:'Homer'})-[:married_to]->(:Person {name:'Marge'})")

This ends up creating two more nodes, and then connecting them. Is there some way to fetch the original two nodes in order to connect them?

1

1 Answers

0
votes

Yes, MATCH to the nodes first and then MERGE the relationship between them

MATCH (homer:Person {name:'Homer'}), (marge:Person {name:'Marge'})
MERGE (homer)-[:married_to]-(marge)

You'll want to have an index on :Person(name) so the initial lookups are fast.

We have a knowledge base article on understanding how MERGE works that can help you get a better grasp on some of the more subtle points of the MERGE clause.