2

I'm trying to delete an entire list starting from a given node to the end of the list.

Where is the list of the root,relationship and child nodes. The child nodes can have an undetermined nodes.

(r:Root {name:'masterDoc'})<-[p:previous]<-(s1:schema)<-[p1:previous]<-(s2:schema)<-[pn:previous]<-(sn:Schema)

When I run the cypher query below I'm getting a Type mismatch: expected Node, Path or Relationship but was Collection

MATCH (n:`Root` {name:'masterDoc'})-[r:previous*]-(s) delete s,r,n

Any Idea? 

langlauf.io
  • 3,009
  • 2
  • 28
  • 45
Andre Rubnikowich
  • 419
  • 1
  • 3
  • 10

1 Answers1

3

You want to pull out the longest path of nodes, iterate over the relationships and delete each one and then iterate over the nodes and delete them.

UPDATED ANSWER

Improvements to Cypher since this answer was posted allow now for nodes to be detached and deleted with a single command.

// match the path that you want to delete
MATCH p=(:Root {name: 'masterDoc'} )-[:previous*]->() 
WITH p

// order it in descending order by length
ORDER by length(p) desc

// grab the longest one
LIMIT 1

// delete all of the relationships and their nodes
DETACH DELETE p

OLDER ANSWER

NOTE: This assumes that each node in the path is no longer anchored to anything other than the nodes in the path otherwise they will not be able to be removed.

// match the path that you want to delete
match p=(:Root {name: 'masterDoc'} )-[:previous*]->() 
with p
// order it in descending order by length
order by length(p) desc
// grab the longest one
limit 1
// delete all of the relationships
foreach (r in relationships(p) | delete r)
// delete all of the remaining nodes
foreach (n in nodes(p) | delete n)
Dave Bennett
  • 10,996
  • 3
  • 30
  • 41
  • does not make sense to me, why do a foreach then delete? – tim Oct 25 '19 at 00:29
  • That is just how `FOREACH` is structured. It is really just `FOREACH( loop control structure | mutating operation )`. I updated the answer to reflect some changes in cypher that allow for a new improved approach. – Dave Bennett Oct 25 '19 at 11:51
  • uh I mean why not delete like this? `(p:Root {name: 'masterDoc'} )-[:previous*]->() DETACH DELETE p` – tim Nov 22 '19 at 21:50
  • 1
    I like it. I will update the answer. For whatever reason I though DELETE would only operate on a node or a relationship and not a path. I presume you mean the path and not the node p in your query. thanks. – Dave Bennett Nov 22 '19 at 23:52