Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Neo4j: MATCH, CREATE, MERGE

Introduction

This lesson explores the essential Neo4j commands: MATCH, CREATE, and MERGE. These commands are fundamental to querying and manipulating graph data using Cypher, Neo4j's query language.

Key Concepts

  • Cypher: The query language for Neo4j.
  • Graph Database: A database that uses graph structures to represent and store data.
  • Nodes and Relationships: The core components of graph databases.

MATCH

The MATCH clause is used to find nodes and relationships in the graph.

Example:


MATCH (n:Person {name: "Alice"})
RETURN n
            

This query retrieves the node representing a person named Alice.

CREATE

The CREATE clause is used to create new nodes and relationships.

Example:


CREATE (n:Person {name: "Bob"})
RETURN n
            

This command creates a new node for a person named Bob.

MERGE

The MERGE clause is a combination of MATCH and CREATE. It ensures that a pattern exists in the graph, creating it if it does not.

Example:


MERGE (n:Person {name: "Alice"})
RETURN n
            

If a node with the name Alice exists, it is returned; otherwise, it is created.

Best Practices

  • Use MATCH for read operations to avoid unintended data modifications.
  • Use CREATE when you need to add new elements.
  • Use MERGE to prevent duplicates and ensure unique nodes or relationships.

FAQ

What is the difference between MATCH and MERGE?

MATCH only retrieves data without modifying the graph, while MERGE ensures that a specified pattern exists, creating it if it does not.

Can I use MATCH without a WHERE clause?

Yes, you can use MATCH without a WHERE clause to retrieve all nodes of a specific label.

What happens if I use CREATE with an existing node?

Using CREATE with an existing node will result in a duplicate node unless the node is uniquely defined by its properties.