Thursday, October 29, 2020

Neo4j - Create a Relationship using Cypher

 MATCH (a:Artist),(b:Album)

WHERE a.Name = "Strapping Young Lad" AND b.Name = "Heavy as a Really Heavy Thing"

CREATE (a)-[r:RELEASED]->(b)

RETURN r



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. a and 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: (a)-[r:RELEASED]->(b).


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.



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:



MATCH (a:Artist),(b:Album),(p:Person)

WHERE a.Name = "Strapping Young Lad" AND b.Name = "Heavy as a Really Heavy Thing" AND p.Name = "Devin Townsend" 

CREATE (p)-[pr:PRODUCED]->(b), (p)-[pf:PERFORMED_ON]->(b), (p)-[pl:PLAYS_IN]->(a)

RETURN a,b,p




References:

https://www.quackit.com/neo4j/tutorial/neo4j_create_a_relationship_using_cypher.cfm

No comments:

Post a Comment