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
.