Skip to content

Merging nodes

Farhad Nowzari edited this page May 18, 2024 · 1 revision

Merging nodes in cypher is like upserting a node (Update or Insert).

How

The merge method is available under the NodeSet and working with it, is as the same as Creating nodes, however there is one twist which you need to take care of.

To be able to merge nodes appropriately, make sure your node have at least one Identifier.

public class Person {
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

if you have a person like the model above and you with to merge it out of the box, the cypher will look like the following:

MERGE (p:Person) SET p.Id=$id, p.FirstName=$firstName, p.LastName=$lastName

As you see, this merge may cause some issues and bugs. There is no difference between this merge and a create. To make a difference, let's add this line to the Person's INodeConfiguration.

builder.HasIdentifier(x => x.Id);

Now when you merge, the cypher will be like this:

MERGE (p:Person { p.Id=$id }) SET p.FirstName=$firstName, p.LastName=$lastName

Now if a person with $id exists it will update it, otherwise will create it.

Enforce identifiers

As you see, if a developer misses to configure identifiers, you may have annoying bugs. In order to prevent this, it is possible to enforce the identifiers which means a merge must have at lease one identifier.

To do so, on adding neo4j as a dependency you need to add this line:

builder.Services.AddNeo4j<ApplicationGraphContext>(builder.Configuration, options =>
{
    options.EnforceIdentifiers = true; //enforces the identifiers
    options
        .ConfigureFromAssemblies(typeof(Program).Assembly);
});
Clone this wiki locally