The CREATE
clause is used to create nodes and relationships in a graph.
​Creating nodes​
​Creating a single node​
​Creating multiple nodes​
​Creating a path​
Use the following query to create a single node. The RETURN
clause is used to return results. A newly created node can be returned in the same query.
CREATE (n)RETURN n;
Output:
+----+| n |+----+| () |+----+
You can also specify a label while creating a node.
CREATE (n:Country)RETURN n;
Output:
+------------+| n |+------------+| (:Country) |+------------+
If you wish to add multiple labels to a node, use the following syntax:
CREATE (n:Country:City)RETURN n;
Output:
+-----------------+| n |+-----------------+| (:Country:City) |+-----------------+
A node can be created with initial properties.
CREATE (n:Country { name: 'San Marino', continent: 'Europe' })RETURN n;
Output:
+------------------------------------------------------+| n |+------------------------------------------------------+| (:Country {continent: "Europe", name: "San Marino"}) |+------------------------------------------------------+
To create multiple nodes, separate them with a comma.
CREATE (n:Country), (m:City)RETURN n,m;
Output:
+------------+------------+| n | m |+------------+------------+| (:Country) | (:City) |+------------+------------+
To create a relationship between two nodes, we need to specify which nodes either by creating them or filtering them with the WHERE
clause.
CREATE (c1:Country { name: 'Belgium' }), (c2:Country { name: 'Netherlands' })CREATE (c1)-[r:BORDERS_WITH]->(c2)RETURN r;
Output:
+----------------+| r |+----------------+| [BORDERS_WITH] |+----------------+
If the nodes already exist, the query would look like this:
MATCH (c1:Country),(c2:Country)WHERE c1.name = 'Belgium' AND c2.name = 'Netherlands'CREATE (c1)-[r:NEIGHBOURS]->(c2)RETURN r;
Output:
+--------------+| r |+--------------+| [NEIGHBOURS] |+--------------+
You can add properties to a relationship at the time of creation.
MATCH (c1:Country),(c2:Country)WHERE c1.name = 'Belgium' AND c2.name = 'Netherlands'CREATE (c1)-[r:BORDERS_WITH { length: '30KM' }]->(c2)RETURN r;
Output:
+---------------------------------+| r |+---------------------------------+| [BORDERS_WITH {length: "30KM"}] |+---------------------------------+
When creating a path, all of the parts of the pattern that don't exist will be created.
CREATE p=((n:Country { name: 'Belgium' })-[r:BORDERS_WITH { length: '30KM' }]->(m:Country { name: 'Netherlands' }))RETURN p;
Output:
+------------------------------------------------------------------------------------------------+| p |+------------------------------------------------------------------------------------------------+| (:Country {name: "Belgium"})-[BORDERS_WITH {length: "30KM"}]->(:Country {name: "Netherlands"}) |+------------------------------------------------------------------------------------------------+