Course contentsShow
← System Design
Lesson 462 of 1,91913. NoSQL: Graph DatabasesFree lesson

Creating Nodes and Relationships

Using CREATE and MERGE to add nodes with labels, properties, and directed relationships to the graph.

Creating Nodes and Relationships

You'll learn: How to use CREATE and MERGE in Cypher to add nodes with labels, properties, and directed relationships to your graph database.

Core Idea

In Neo4j, you build your graph by creating nodes (entities) and relationships (connections between them). The Cypher query language provides two primary commands: CREATE for adding new data unconditionally, and MERGE for ensuring a node or relationship exists without creating duplicates.

CREATE: Adding New Elements

Use CREATE to add nodes with labels and properties:

CREATE (p:Person {name: 'Alice', age: 30})

This creates a node labeled Person with two properties. Think of labels like categories and properties like attributes describing that entity.

To create a relationship between nodes:

CREATE (a:Person {name: 'Alice'})-[:FOLLOWS]->(b:Person {name: 'Bob'})

The arrow -> makes the relationship directed from Alice to Bob. The :FOLLOWS is the relationship type, acting like a verb connecting the two nodes.

MERGE: Avoiding Duplicates

CREATE always adds new data. If you run it twice, you get duplicate nodes. MERGE is smarter—it finds existing matches or creates them if missing:

MERGE (p:Person {name: 'Alice'})

This finds Alice if she exists, or creates her if she doesn't. You can combine MERGE for nodes and relationships to build idempotent graph patterns safely.

Why It Matters

These operations are the foundation of populating your graph database. CREATE is fast for bulk loading; MERGE prevents duplicate data when you're unsure whether entities already exist.

Key Takeaway:
Use CREATE to add nodes and relationships unconditionally; use MERGE to ensure they exist exactly once, making your graph operations safe and duplicate-free.