Delete node and relationships using cypher query over REST API

11,443

Solution 1

MATCH n-[r]-() will only match the node if there is at least one relationship attached to it.

You want to make the relationship match optional: MATCH n-[r?]-()

Also, you need to delete the relationships before the node.

So, your full query is:

START n=node(1916)
MATCH n-[r?]-()
DELETE r, n

Solution 2

For neo4j 2.0 you would do

START n=node(1916)
OPTIONAL MATCH n-[r]-()
DELETE r, n;

Solution 3

Both START and the [r?] syntax are being phased out. It's also usually not advised to directly use internal ids. Try something like:

match (n{some_field:"some_val"}) optional match (n)-[r]-() delete n,r

(see http://docs.neo4j.org/refcard/2.1/)

Solution 4

And again there is a pretty syntax change. Neo4j 2.3 introduces the following:

MATCH (n {id: 1916})
DETACH DELETE n

Detach automatically deletes all in- and outgoing relationships.

Solution 5

The question mark(?) is not supported in Neo4J 2.0.3, so the answer would be to use OPTIONAL MATCH

START n=node(nodeid) OPTIONAL MATCH n-[r]-() DELETE r, n;

Share:
11,443

Related videos on Youtube

user2926169
Author by

user2926169

Updated on June 04, 2022

Comments

  • user2926169
    user2926169 almost 2 years

    I'm playing with 2.0 M6 neo4j server (oracle jdk7 on win7 64).

    I'm trying to delete a node and its relationships using a single cypher query over the REST API.

    The query I create (which works if I run it in the browser UI) looks like:

    START n = node( 1916 ) MATCH n-[r]-() DELETE n, r
    

    Which by the time I put it through gson comes out as:

    {"query":"START n \u003d node( 1916 ) MATCH n-[r]-() DELETE n, r"}
    

    Which when sent to the server gets the response:

    {
      "columns" : [ ],
      "data" : [ ]
    }
    

    My test fails because the node can still be found in neo4j server by its id...

    If I simplify my query to just delete a node (that has no relationships) so its:

    START n = node( 1920 )  DELETE n
    

    Which becomes

    {"query":"START n \u003d node( 1920 )  DELETE n"}
    

    Then the node is deleted.

    Have I missed something?

    Thanks, Andy

  • user2926169
    user2926169 over 10 years
    That makes perfect sense and having made the changes you suggest it works perfectly :) Thank you.
  • Nadjib Mami
    Nadjib Mami almost 10 years
    This is valide in Neo4j 1.x version. Neo4j 2 introduced a new syntax: OPTIONAL MATCH n-[r]-(). Refer to Leland Cope answer.
  • George Birbilis
    George Birbilis about 9 years
    so to delete all nodes (including disconnected ones) and their relationships you do MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r (nice that it works in a single line too)