Reputation: 99
With Neo4J, when creating a relationship, I would like to create a node if it does not exist. I can do this using MERGE, but I would like the created node to be of a different type. Is there a way to check if the node exists and create a different node if not.
My current request:
MATCH (a:Person {name:'Jon'})
MERGE (b:City {name: 'Paris'})
CREATE (a)-[:work]->(b)
Here we assume that the person exists in all cases, but the city not necessarily. This request works and creates a new city if it does not exist.
My problem is that I want to keep a track of the new city by giving them the type "NewCity" instead of "City".
Upvotes: 0
Views: 1027
Reputation: 8950
Ideally, you would write it like this:
MATCH (a:Person {name:'Jon'})
MERGE (b:City {name: 'Paris'})
ON CREATE
SET b:NewCity
ON MATCH
REMOVE b:NewCity // <-- spoiler alert: this does NOT work :(
CREATE (a)-[:work]->(b)
You need to keep the City
label when you first create the node, otherwise the next time the query runs, MERGE
won't match the node anymore.
Unfortunately, ON MATCH REMOVE b:NewCity
is not supported, so you have to introduce an extra SET that gets removed afterwards:
MERGE (b:City {name: 'Paris'})
ON CREATE
SET b:NewCity
ON MATCH
SET b.temp = ''
WITH *
CALL { WITH b
WITH b WHERE b.temp IS NOT NULL
REMOVE b.temp
REMOVE b:NewCity
}
Upvotes: 1