Sten Petrov
Sten Petrov

Reputation: 11040

Find a graph node by a field, update all other fields

I have a Neo4J graph database where I want to store users and relationships between them.

I want to be able to update a User node that I find them by GUID with data contained in a .Net User object. Ideally I'd like to know how to do that in Neo4JClient but even plain Cypher query would do.

Ideally I'd like to use the whole object, not knowing what properties have been modified, and replace all of them - including array properties - unlike the example below that knows PhoneNumber is to be updated

Something like this:

MATCH (n:`User` {Id:'24d03ce7-8d23-4dc3-a13b-cffc0c7ce0d8'}) 
MERGE (n {PhoneNumber: '123-123-1234'})
RETURN n

The problem with the code above is that MERGE redefines the n

and I get this error:

n already declared (line 2, column 8) "MERGE (n {PhoneNumber: '123-123-1234'})" ^

Upvotes: 0

Views: 88

Answers (1)

cybersam
cybersam

Reputation: 67044

  1. If all you want to do is completely replace all the properties of existing nodes, do not use MERGE. You should just use MATCH, and SET all the properties. Something like this:

    MATCH (n:`User` {Id:'24d03ce7-8d23-4dc3-a13b-cffc0c7ce0d8'}) 
    SET n = {PhoneNumber: '123-123-1234', Age: 32}
    RETURN n;
    
  2. On the other hand, if you want to create a new node iff one with the specified Id does not yet exist, and you also want to completely replace all the properties of the new or existing node, you can do this:

    MERGE (n:`User` {Id:'24d03ce7-8d23-4dc3-a13b-cffc0c7ce0d8'}) 
    SET n = {PhoneNumber: '123-123-1234', Age: 32}
    RETURN n;
    

Note: in the above queries, all the existing properties of n would be deleted before the new properties are added. Also, the map assigned to n in the SET clause can be passed to the query as a parameter (so no hardcoding is needed).

Upvotes: 1

Related Questions