Create Relationships in Neo4j
In Neo4j, relationships are used to connect nodes and describe the nature of the connection. Creating relationships is a fundamental operation in graph databases, allowing you to build rich, interconnected data models.
Syntax
To create a relationship in Neo4j, you use the CREATE
clause, followed by a pattern that specifies the nodes and relationship to be created:
CREATE (node1)-[relationship:RELATIONSHIP_TYPE]->(node2)
Here, node1
and node2
are existing nodes in the graph, and relationship
is an identifier for the new relationship. RELATIONSHIP_TYPE
is a user-defined string that describes the type of relationship being created.
Example
Let's say we have the following nodes in our graph:
(:Person {name: "Alice"})
(:Movie {title: "The Matrix"})
We can create a relationship between these nodes using the following query:
MATCH (p:Person {name: "Alice"}), (m:Movie {title: "The Matrix"})
CREATE (p)-[:ACTED_IN]->(m)
In this example, we're creating a :ACTED_IN
relationship between the Person
node with name Alice
and the Movie
node with title The Matrix
.
Output
After executing the query, you can verify that the relationship was created using the MATCH
clause:
MATCH (p:Person {name: "Alice"})-[:ACTED_IN]->(m:Movie {title: "The Matrix"})
RETURN p, m
This should return both nodes, connected by the ACTED_IN
relationship.
╒═══════════════════════════════════════════════════╕
│"p" │
╞═══════════════════════════════════════════════════╡
│{"name":"Alice","_id":0} │
└───────────────────────────────────────────────────┘
╒═══════════════════════════════════════════════════╕
│"m" │
╞═══════════════════════════════════════════════════╡
│{"title":"The Matrix","_id":2} │
└───────────────────────────────────────────────────┘
Explanation
The CREATE
clause creates a directed relationship between the Person
node and the Movie
node, with the identifier ACTED_IN
. This relationship describes the fact that the person Alice
acted in the movie The Matrix
.
Use
Creating relationships in Neo4j is an important operation when building graph databases. Relationships connect nodes and describe the nature of the connection, giving meaning to the data in the graph.
Important Points
- The
CREATE
clause is used to create relationships in Neo4j. - Relationships are created between existing nodes in the graph.
- The syntax for creating relationships includes a pattern that describes the nodes and relationship to be created.
- Relationships are directed, and can have user-defined labels.
- Relationships in Neo4j can have properties, which describe the nature of the relationship.
Summary
Creating relationships is a fundamental operation in Neo4j, allowing you to build rich, interconnected data models. Relationships are created with the CREATE
clause, and describe the nature of the connection between nodes. Relationships can be directed, labeled, and can have properties, making it easy to build complex, multi-dimensional graphs.