Neo4j - Create a Relationship using Cypher
Just like creating nodes in Neo4j, we can use the
CREATE statement to create relationships between those nodes.
The statement for creating a relationship consists of
CREATE, followed by the details of the relationship that you're creating.
Let's create a relationship between some of the nodes that we created previously. First, let's create a relationship between an artist and an album.
Here's the Cypher
CREATE statement to create the above relationship:
Explanation of the Above Code
First, we use a
MATCH statement to find the two nodes that we want to create the relationship between.
There could be many nodes with an Artist or Album label so we narrow it down to just those nodes we're interested in. In this case, we use a property value to filter it down. We use the Name property that we'd previously assigned to each node.
Then there's the actual
CREATE statement. This is what creates the relationship. In this case, it references the two nodes by the variable name (i.e.
b) that we gave them in the first line. The relationship is established by using an ASCII-code pattern, with an arrow indicating the direction of the relationship:
We give the relationship a variable name of
r and give the relationship a type of
RELEASED (as in "this band released this album"). The relationship's type is analogous to a node's label.
Adding More Relationships
The above example is a very simple example of a relationship. One of the things that Neo4j is really good at, is handling many interconnected relationships.
Let's build on the relationship that we just established, so that we can see how easy it is to continue creating more nodes and relationships between them. So we will create one more node and add two more relationships.
We'll end up with the following graph:
So let's start by creating the node for Devin Townsend:
Now create the relationships and return the graph:
You should now see the graph as in the previous screenshot.