cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Delete node and relation based on match specific node

Peter_Lian
Node Clone

The Figure show below

Peter_Lian_1-1668415081681.png

 

Orange Node only three : cmd.exe, ipconfig.exe, wsmpro.exe (All of them are "Process" node)

Orange relation : create_process_to

I want to delete all the node and relation if the node that linked each others by create_process_to do not involved the "wsmpro.exe" node. That is, the result should be the following

Peter_Lian_2-1668415224369.png

Since others do not involved wsmpro.exe node. I tried 

 

MATCH (r)-[create_process_to]->()
WHERE NOT r.image = "wsmpro.exe"
DETACH DELETE r
 
But it does not work since the above figure become the below
 
Peter_Lian_0-1668415720697.png

which is not what I want.

 

How can I do? Thanks.

 

1 ACCEPTED SOLUTION

Try this. 

match (p:Process{image:"wsmpro.exe"})
match path=(p)-[*]-()
unwind nodes(path) as node
with collect(distinct id(node)) as nodeIdsToKeep
match(n:Process) 
where not id(n) in nodeIdsToKeep
detach delete n

View solution in original post

6 REPLIES 6

Ajithkumar
Node
You have delete the relations also , and kindly check those values are same dataType
 
MATCH (r)
WHERE NOT r.image = "wsmpro.exe"
OPTIONAL MATCH (r)-[relation:create_process_to]->() 
DELETE r,relation 

I tried What you said, but the following shows

 

Cannot delete node<896>, because it still has relationships

If I add DETACH, then all the node and edge just disappear.

glilienfield
Ninja
Ninja

It is a little more complicated, since what you want is to keep all nodes of each subgraph anchored on each wspro.exe node. I think what you need to do is 1) match on all wsmpro.exe nodes, 2) expand on each to get each node’s subgraph of nodes, 3) get the list of node ids from all the nodes across each subgraph, 4) match all nodes whose node id is not in the set of node id’s just derived, and 5) detach delete each of the nodes matched. 

If you confirm my understanding is correct, I can write a query if you need help. 

Yes you're correct, that is the method which I have thought earlier but I can not get the result correctly since I'm not very familiar with Cypher.

It would be a big help if you could give me a help, thanks!

Try this. 

match (p:Process{image:"wsmpro.exe"})
match path=(p)-[*]-()
unwind nodes(path) as node
with collect(distinct id(node)) as nodeIdsToKeep
match(n:Process) 
where not id(n) in nodeIdsToKeep
detach delete n

Appreciate, this idea gives me a biggggg help (not only in this case)! 

Nodes 2022
Nodes
NODES 2022, Neo4j Online Education Summit

All the sessions of the conference are now available online