Search code examples
cyphermemgraphdbopencypher

What is a correct way to update a property using Cypher?


I have nodes that have first name. I want to update all of the names John to Johan. Is there a difference between this two queries? The end result seems the same to me.

Query 1

MATCH (p:Person)
WHERE p.name= "John"
SET p += {name: "Johan"};

Query 2

MATCH (p:Person)
WHERE p.name= "John"
SET p.name="Johan";

I've run the PROFILE for both queries, and they are rather similar.

PROFILE MATCH (p:Person) WHERE p.name= "John" SET p += {name: "Johan"};

enter image description here

PROFILE MATCH (p:Person) WHERE p.name= "John" SET p.name="Johan";

enter image description here


Solution

  • There certainly is a "difference", since Query 1 uses the SetProperties operation to copy all the properties from a map (that happens to have a single property), whereas Query 2 uses SetProperty to set a single property from a literal.

    I think the most important reason for using the += syntax occurs when there are a lot of properties to be set. In that case, it is a lot easier (and less brittle) to write:

    SET p += x
    

    than:

    SET p.a = x.a, p.b = x.b, p.c = x.c, ...
        or
    SET p.a = 123, p.b = true, p.c = 'Fred', ...
    

    Especially if processing earlier in the query provides x for free. But even if you have to create the x map, the result is more readable:

    WITH p, {a: 123, b: true, c: 'Fred', ...} AS x
    SET p += x