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.

Best way to do this pattern: add node then add edge from that node

Rogie
Node Link

I find myself often implementing this sort of pattern: I want to add a new node, and then connect it to some other nodes that may already be present in the graph. My current way of doing this is:

First merge the new node into the graph:
Merge (u:User {user_name:"Wayne"})
Now that the new user node is added, I want to connect it some, say, movie node:

Match (m:Movie {name:"Matrix"}) with m
Match (u:User {user_name:"Wayne"}) with u, m
Merge (u)-[:LIKES]->(m)

Is there a way to combine this into a single query?

If I just do

Match (m:Movie {name:"Matrix"}) with m
Merge (u:User {user_name:"Wayne"})-[:LIKES]->(m)

then the problem is that if Wayne already exists in the graph but is not connected to Matrix, then we get a second Wayne.

2 REPLIES 2

jsmccrumb
Graph Buddy

The MERGE followed by the MATCH MATCH MERGE will sometimes run faster than doing it all at once, but you can do:

Match (m:Movie {name:"Matrix"})
MERGE (u:User {user_name:"Wayne"})
Merge (u)-[:LIKES]->(m)

I removed the WITH statements since they are not required in this case (MATCH followed by two merges). Good luck!

match(m:Movie{name:'Abc'})
create(m)<-[:produced]-(p:Producer{name:'Jimmy'})