DELETE

更新时间:
复制 MD 格式

Use the DELETE clause to remove nodes, relationships, or paths from a graph. To remove properties or labels without deleting the element, see REMOVE.

Key concepts

Terminal clause: A DELETE clause with no following clause is a terminal clause. When a Cypher query ends with a terminal clause, the cypher() function returns no rows — but the SQL call still requires a column list. Define a single placeholder column; no data is returned in that variable.

Node deletion constraint: You cannot delete a node without deleting the edges that start from or end at that vertex. Either delete the relationships explicitly before deleting the node, or use DETACH DELETE to remove both in one step.

Scenarios

  1. Delete isolated nodes

  2. Delete nodes and their relationships

  3. Delete relationships

  4. Delete all nodes and relationships

  5. Return a deleted node

Delete isolated nodes

DELETE removes a node only if it has no relationships.

SELECT *
FROM cypher('graph_name', $$
    MATCH (v:Useless)
    DELETE v
$$) as (v agtype);

Nodes with the Useless label that have no relationships are deleted. The query returns no rows.

 v
---
(0 rows)

Use DETACH DELETE to delete a node along with all its relationships.

Delete nodes and their relationships

DETACH DELETE removes a node and all relationships connected to it in a single operation.

SELECT *
FROM cypher('graph_name', $$
    MATCH (v:Useless)
    DETACH DELETE v
$$) as (v agtype);

All nodes with the Useless label, along with any connected relationships, are deleted. The query returns no rows.

 v
---
(0 rows)

Delete relationships

To delete a relationship without deleting its nodes, match the relationship and pass its variable to DELETE.

SELECT *
FROM cypher('graph_name', $$
    MATCH (n {name: 'Andres'})-[r:KNOWS]->()
    DELETE r
$$) as (v agtype);

The KNOWS relationship from the node named 'Andres' is deleted. The nodes remain. The query returns no rows.

 v
---
(0 rows)

Delete all nodes and relationships

To clear an entire graph, match all nodes and use DETACH DELETE.

SELECT *
FROM cypher('graph_name', $$
    MATCH (n)
    DETACH DELETE n
$$) as (v agtype);

All nodes and all relationships in the graph are deleted. The query returns no rows.

 v
---
(0 rows)

Return a deleted node

Combine DELETE with RETURN to retrieve the node data before it is removed.

SELECT *
FROM cypher('graph_name', $$
    MATCH (n {name: 'A'})
    DELETE n
    RETURN n
$$) as (a agtype);

The node is deleted and its data is returned.

                                    a
----------------------------------------------------------------------------
{"id": 281474976710659, "label": "", "properties": {"name": "A"}}::vertex
(1 row)
RETURN after DELETE returns the node's data as it existed before deletion.

Related topics

  • REMOVE — remove properties or labels from a node or relationship without deleting the element