7

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.

stdob--
  • 28,222
  • 5
  • 58
  • 73
user3180997
  • 1,836
  • 3
  • 19
  • 31

3 Answers3

13

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
barthr
  • 430
  • 7
  • 15
  • 2
    WITH has nothing to do here, your query is correct but it is more related that he should use CREATE instead of MATCH for creating first the user node, switch your CREATE and MATCH and you don't need WITH, anyway +1 – Christophe Willemsen Jan 25 '16 at 01:08
3

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'})
Max Rasguido
  • 457
  • 6
  • 27
  • 3
    This only works the first time you run it. On subsequent runs for other people it will create the university again because MERGE creates the whole path unless the whole path already exists. – bikeman868 Jun 16 '20 at 23:24
0

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)

Mvde
  • 141
  • 6