user3180997
user3180997

Reputation: 1926

Neo4J - Creating Relationship on existing nodes

I am new to Neo4J and I am looking to create a new relationship between an existing node and a new node.

I have a university node, and person node.

I am trying to assign a new person to an existing university.

I am trying to following code:

MATCH (p:Person {name:'Nick'}), (u:University {title:'Exeter'}) CREATE (p)-[:LIKES]->(u)

So in the above code: MATCH (p:Person {name:'Nick'}) is the new user

AND (u:University {title:'Exeter'}) is the exisiting univeristy.

But it is coming back (no changes, no rows)

I have even tried the query without the MATCH part but no luck either.

I have looked at few similar answers but they didn't seem to work either.

Any help would be very much appreciated. Thank you.

Upvotes: 7

Views: 12478

Answers (3)

Max Rasguido
Max Rasguido

Reputation: 457

You could also use a MERGE statement as per the docs:

MERGE either matches existing nodes and binds them, or it creates new data and binds that. It’s like a combination of MATCH and CREATE that additionally allows you to specify what happens if the data was matched or created.

You would do a query like

MERGE (p:Person {name:'Nick'})-[:LIKES]->(u:University {title:'Exeter'})

Upvotes: 3

barthr
barthr

Reputation: 440

Match before u create new one, as suggested in the comments!

MATCH(u:University {title:'Exeter'})
CREATE(p:Person {name:'Nick'})
CREATE(p)-[w:LIKES]->(u)
return w

Upvotes: 13

Mvde
Mvde

Reputation: 141

It is because when you match you search for a nodes in your db. The db says i can't make the realtion "when the nodes dont exist".

Luckily there is something called merge it is like a match +create when he does not find the whole path he creates it. it should be something like merge 'node1' merge'node2' create(node1)[]->(node2)

Upvotes: 0

Related Questions