1
votes

I have a tree structure, like node(8) has two children node(13) and node(14). How can I delete all children when I delete node(8) by cyhper.

I write cypher like this:" START r=node(8) MATCH r-[:children*0..]-> d With d Match d-[x]-() Delete d,x"

It should work, but actually it only delete node(8) and get some error. I find that actually it's trying to delete a collection like this.

  • ---d-------------------r
  • Node(8)----------Rel(16)
  • Node(8)----------Rel(17)
  • Node(9)----------Rel(16)
  • Node(10)---------Rel(17)

And after cyhper delete first Node(8), it try to delete Node(8) for second time and get error because it doesn't exist anymore.

It's wired cause when I write cypher like this: "START r=node(8) MATCH r-[:children*0..]-> d Return d" It returns:

  • ---d---
  • Node(8)
  • Node(8)
  • Node(9)
  • Node(10)

And it's right. But as we know, I can't delete them with relationship on them, so I need to write a cypher with "WITH":

"START r=node(8) MATCH r-[:children*0..]-> d With d Match d-[x]-() Return d,x"

And it get the wrong result again.

  • ---d-------------------r
  • Node(8)----------Rel(16)
  • Node(8)----------Rel(17)
  • Node(9)----------Rel(16)
  • Node(10)---------Rel(17)

Can anyone help me? It's really depressed. I really like neo4j, but I find the "Delete" part is such tough. Why not just use "Force Delete" and make Neo4j to auto delete relationships just like this:

"START r=node(8) MATCH r-[:children*0..]-> d FORCE DELETE d"

And btw, why can't use distinct in "Delete" part?

1

1 Answers

2
votes

There was a bug in an earlier neo4j version--I don't remember which. Which version are you using? You should be able to do this sort of query without an error about a node existing.

I also agree that this syntax should be easier. This is how I got it to work.

start n=node(8) // start at the node you want to delete
match n-[r:children*0..]->m, n-[anyothers?]-() // find your pattern to delete, and find any other relationships coming off of n (inbound/non :children)
foreach(x in r: delete x) // delete all the relationships for children
delete m, n, anyothers; // delete the nodes and any other relationships