Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j delete a node and return the deleted node

Tags:

neo4j

cypher

Christmas everyone,

I have a simple question. I want to delete a node with/without relationships in Neo4j and return the deleted node and/or its specific property. Something in the following lines (below doesn't work)

MATCH(j:JOB) where j.job_id= "1" DELETE j, return j;  

I can do the above task in two different requests, query the node that is to be deleted and then delete it but, I want to know whether it is possible to do it in single statement.

I wonder if there is a way to store the node in a different placehoder and then delete the node and return the placeholder. I am new to Neo4j, need suggestions.

I have come across this post which is old and I could not get it work with my version of Neo4j. I use Neo4j 2.3.1

like image 846
Raf Avatar asked Dec 26 '15 15:12

Raf


3 Answers

You can use a WITH clause to alias the data (properties) you want to return and delete the node in the same query:

//WITH j, needed to add j after WITH for cypher to work.

MATCH(j:Job) where j.job_id = "1" 
WITH j, j.industry AS industry, j.name AS name
DELETE j
RETURN industry, name

See this answer.

like image 59
William Lyon Avatar answered Oct 18 '22 04:10

William Lyon


There may be a simpler way to accomplish what you want.

Rather than copy the node, why not just leave it the same, change its label (so it doesn't interfere with the rest of your model) and then return that node?

Something like this:

MATCH (j:JOB { job_id = '1' })
OPTIONAL MATCH (j)-[r]-(n)
REMOVE j:JOB
DELETE r
SET j:RecycleBin_JOB
RETURN j;

Copying the node to store it seems like a waste of time since you already have one. Just return that one, and adjust the labels and relationships so it doesn't interfere with the rest of your model.

like image 24
FrobberOfBits Avatar answered Oct 18 '22 03:10

FrobberOfBits


If you want all the properties of the deleted node. This might help you

Match (n:Product)
WITH n, properties(n) AS m
DETACH DELETE n
RETURN m

I was having a similar issue, above code worked for me, Good Day.

like image 3
Dev Gaud Avatar answered Oct 18 '22 04:10

Dev Gaud