neo4jcypherneo4j-graphql-js

How to update properties of nodes while merging in neo4j


I want to merge my contacts with existing available contact nodes, but there is a minor issue I am facing.

I want to replace the name only if the name property does not exist if exist I do not want to touch it let it be as it is if the property is a null id empty string then I want to replace it with a new name property

any idea how it can be done in cypher I am giving an example code below which I was trying with my best understanding

MATCH (me:User {id: $id})
      UNWIND $contacts AS c
      FOREACH (contact in c |
      MERGE (knows:User {number:contact.number}) 
      MERGE (me)-[:KNOWS]->(knows)
       SET
        knows.name = coalesce(knows.name, contact.name),
        knows.email = coalesce(knows.email, contact.email),
        knows.id =  coalesce(knows.id, contact.id),
        knows.anonymous = coalesce(knows.anonymous, randomUUID()),
      )
     RETURN knows

     const session = MyDriver.session();
    const result = await session.run(cypher, { id, contacts: myConctacts });
    session.close();


Solution

  • You can use coalesce where you provide a value in case the property doesn't exist, for eg :

    SET knows.name = coalesce(knows.name, contact.name)
    

    Reference : https://neo4j.com/docs/cypher-manual/current/functions/scalar/#functions-coalesce