Javatpoint Logo
Javatpoint Logo

Neo4j Merge Command

Neo4j MERGE command is a combination of CREATE and MATCH command. This command is used to search for a given pattern in the graph. If it exists in the graph then it will return the result otherwise, it creates a new node/relationship and returns the results.

Using MERGE command you can do the following things:

  • Merge a node with label.
  • Merge a node with properties.
  • OnCreate and OnMatch.
  • Merge a relationship.

Syntax:

Example:

First create two nodes in the Neo4j database with labels sachin and Ind. Create a relationship of type "BATSMAN_OF" from sachin to Ind.

Neo4j Merge command 1

Merge a Node with a Label

MERGE clause is used to merge a node in the database based on the label. If you try to merge a node based on the label, then Neo4j verifies if there exists any node with the given label. If not, the current node will be created.

Syntax:

Example1:

Let's merge a node "Sehwag" to a label player. Neo4j verifies if there is any node with the label player. If not, it creates a node named "Sehwag" and returns it.

If, there any node with the given label exists, Neo4j returns them all.

Output:

Neo4j Merge command 2

Here are already many nodes with the label player. So there is no need to create another node for merging.

Example2:

Merge a node named "CT" with a label named "Tornament". Since there are no nodes with this label, Neo4j creates a node with the given name and returns it.

Output:

Neo4j Merge command 3

Merge a Node with Properties

You can add properties with the node you merged.

Syntax:

Example:

Output:

Neo4j Merge command 4

OnCreate and OnMatch

OnCreate and OnMatch command are used to indicate whether the node is created or matched. Whenever, we execute a merge query, a node is either matched or created.

Syntax:

Example:

The following example demonstrates the usage of OnCreate and OnMatch clauses in Neo4j. If the specified node already exists in the database, then the node will be matched and the property with key-value pair isFound = "true" will be created in the node. If the specified node doesn't exist in the database, then the node will be created, and within it a property with a key-value pair isCreated ="true" will be created.

Output:

Neo4j Merge command 5

Merge a Relationship

MERGE clause can also be used to merge relationships just like nodes.

See this example which merges a relationship using the MATCH clause in Neo4j. This query tries to merge a relationship named WINNERS_OF between the nodes ?ind? (label: Country & name: India) and ICC (label: Tornament & name: ICC Champions Trophy).


Next TopicNeo4j Set Clause





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA