Search code examples
neo4jcyphergraph-databases

merge and where in neo4j


I have 3 nodes with the following properties and relationships :

LocationNode : location,
PersonNode : fullName, 
CityNode: cityName
LocationNode<-[has_location]-(PersonNode)
PersonNode-[has_city]->(CityNode)

LocationNode is a old node which is to be deleted. LocationNode data is to be moved to new node CityNode. For all PersonNode's who have relation with LocationNode i need to delete that relation and create a new relation with CityNode where LocationNode.location = CityNode.cityName

NOTE : CityNodes are already created in database no need to create a new one.

I tried the following query :

match (n:LocationNode)<-[r:has_location]-(j:PersonNode) delete r with n,j
merge (j)-[r2:has_city]->(h1:CityNode) where n.location = h1.cityName return j

The error i got was that i cant use WHERE condition while using MERGE. can anyone tell me the correct query i can use ?


Solution

  • The condition where can not be used with merge. And since the CityNode node exists, you need to match it, and merge a relationship between it and the PersonNode:

    match (n:LocationNode)<-[r:has_location]-(j:PersonNode) delete r 
    with n, j 
    match (h1:CityNode) where n.location = h1.cityName
    merge (j)-[r2:has_city]->(h1)
    return j