CREATE command
You can use CREATE to insert nodes, relationships, and patterns. To create a person node name Mark:

CREATE (friend:Person {name: ‘Mark’}) RETURN friend

Since Mark is a friend Jennifer, to connect the two, we would have the following query:

MATCH (jennifer:Person {name: ‘Jennifer’})

MATCH (mark:Person {name: ‘Mark’})

CREATE (jennifer)-[rel:IS_FRIENDS_WITH]->(mark)

Bare in mind that the CREATE command does a blind insert, meaning that if we already have Jennifer as a node in the graph database, the CREATE command will just create a duplicate Jennifer nodes. That’s why we have two MATCH commands above!

UPDATE command
We can update existing data using the MATCH and SET commands. The MATCH would be use to find the data we want to modify and the SET is use to add, remove, or update properties. If we want to add the birth date of Jennifer, we would have the following command:

MATCH (p:Person {name: “Jennifer”})

SET p.birthdate = date(‘2020-01-01’)


The query for changing the birthdate would be the same as above with a different date. We could do the same query to set the properties of the relation!

DELETE command
You can only delete a node if it doesn’t have any relationships to other nodes! Therefore, to delete any node, you must first delete the relationships, then delete the node. This is shown in the example below:

MATCH (j:Person {name: ‘Jennifer’})-[r:IS_FRIENDS_WITH]->(m:Person {name: ‘Mark’})


MATCH (m:Person {name: ‘Mark’})


Instead of using two queries as above to delete Mark node, we can use DETACH DELETE to remove any existing relationships Mark has before deleting Mark node:

MATCH (m:Person {name: ‘Mark’})


REMOVE properties
You can use REMOVE or SET to remove properties. Using SET, you would set the property value to null as Neo4j does not store null values. You can also use REMOVE as shown below:

MATCH (n:Person {name: ‘Jennifer’})

REMOVE n.birthdate

MERGE to avoid duplicate data
MERGE first checks if the data exists in the database before doing a select or insert operation. If the data exists, Cypher would return it and make any updates necessary. If the data doesn’t exist, Cypher will create it. If Mark node doesn’t exist in the database and we want to create it, we can use:

MERGE (mark:Person {name: ‘Mark’})


The MERGE works for relationships too. Note that MERGE looks at the ENTIRE pattern that you specify to see whether it should return an existing one or create new ones. If the entire pattern does not exist, Cypher will create it. Therefore, Cypher never does a partial mix of matching and creating! This means that it’s a good practice to MATCH first before doing any MERGING.

MERGE criteria

You can perform different operations depending on the MERGE results by using the ON CREATE and ON MATCH with SET commands. If the MERGE requires Cypher to create, then do X. If the MERGE requires Cypher to match, then do Y.



Data Scientist

Leave a Reply