Creating and updating graphs
On this page
CREATE
Create nodes and relationships. Inline {...} sets properties.
CREATE (:Person {name: 'Ada', age: 36});
CREATE (a:Person {name: 'Ada'})-[:KNOWS {since: 2015}]->(b:Person {name: 'Bob'});
// comma-separated patterns create in order, left to right; a later pattern
// may reuse a variable bound by an earlier one:
CREATE (a:Person {name: 'Eve'}), (b:Person {name: 'Fay'}), (a)-[:KNOWS]->(b);
// create relationships between already-matched nodes:
MATCH (a:Person {name: 'Ada'}), (b:Person {name: 'Cy'})
CREATE (a)-[:KNOWS]->(b);
MERGE
Match the pattern if it exists, else create it — with optional ON CREATE /
ON MATCH side-effects.
MERGE (u:User {id: 1}); // get-or-create
MERGE (u:User {id: 1})
ON CREATE SET u.created = true
ON MATCH SET u.seen = true;
// MERGE can extend already-bound variables:
MATCH (a:User {id: 1})
MERGE (a)-[:OWNS]->(b:Account {no: 'A-1'});
SET
Set properties and add labels. Comma-separate multiple updates.
MATCH (p:Person {name: 'Ada'})
SET p.seen = true, p.age = 37, p:VIP; // two properties + a label
- Setting a property to
nullremoves the key (equivalent toREMOVE):SET p.nick = null. SET p:VIPadds theVIPlabel (no-op if already present).
REMOVE
Remove properties and labels.
MATCH (p:Person {name: 'Ada'})
REMOVE p.seen, p:VIP; // remove a property and a label
DELETE / DETACH DELETE
Delete relationships and nodes.
MATCH (a)-[r:KNOWS]->(b) DELETE r; // delete a relationship
MATCH (p:Person {name: 'Ada'}) DELETE p; // error if p still has relationships
MATCH (p:Person {name: 'Ada'}) DETACH DELETE p; // delete p and its relationships
- Plain
DELETEof a node that still has relationships is an error — useDETACH DELETE. DELETEis idempotent within a statement: an entity bound by several rows is deleted once; a repeat is a no-op.
FOREACH
Run a set of updating clauses once per element of a list, for each input row.
The loop variable is local to the FOREACH; no new binding escapes to the outer
query.
// create three tag nodes
FOREACH (n IN [1, 2, 3] | CREATE (:Tag {v: n}));
// per matched person, attach two child nodes
MATCH (p:Person)
FOREACH (i IN [1, 2] | CREATE (p)-[:HAS]->(:Child {i: i}));
The body may contain CREATE, MERGE, SET, REMOVE, DELETE and nested
FOREACH — but not read clauses (MATCH/WITH/RETURN).
Map and list-property updates
SET n = map replaces properties; SET n += map merges properties. Null values
remove keys. GDB also supports SET n.values[index] = value; an index beyond
the end extends the list with null padding, and an absent property becomes a list.
See element indexes for querying staged list values.
MATCH (p:Person {name:'Ada'}) SET p += {active:true};
MATCH (p:Person {name:'Ada'}) SET p.stages[2] = 'published';
Related articles
Indexes and constraints · Procedure directory · Transactions and concurrency