Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a node exists, if not create

Tags:

neo4j

cypher

Im trying to make a database were everytime a node does't exist it will create a new one and set a relationship between this node and another. If the node exists, both nodes get a relationship.

My problem is that, if I try to connect 2 existing nodes, the 2nd node will be recreated. I tried with MERGE and CREATE UNIQUE, both didnt work.

My exmaple code:

CREATE (test1 name:'1'}) MATCH (n) WHERE n.name = '1' MERGE (n)-[:know {r:'123'}]->(test3 {name:'3'})  MATCH (n) WHERE n.name = '1' MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'}) 

Till here it works but with:

MATCH (n) WHERE n.name = '3' MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'}) 

it creates a new node "2" instead of connect to the one exist.

like image 755
Kapotth Avatar asked Jun 03 '14 12:06

Kapotth


1 Answers

When using MERGE on full patterns, the behavior is that either the whole pattern matches, or the whole pattern is created. MERGE will not partially use existing patterns — it’s all or nothing. If partial matches are needed, this can be accomplished by splitting a pattern up into multiple MERGE clauses. http://docs.neo4j.org/chunked/stable/query-merge.html

MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'}) will try to match the entire pattern and since it does not exist, it creates it. What you can do is:

MERGE (n {name: '3'}) //Create if a node with name='3' does not exist else match it MERGE (test2 {name:'2'}) //Create if a node with name='2' does not exist else match it MERGE (n)-[:know {r:'123'}]->(test2) //Create the relation between these nodes if it does not already exist 
like image 188
Luanne Avatar answered Sep 24 '22 15:09

Luanne