6

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

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you William, exactly what I was looking for, though I had to change the query to add j after WITH keyword.
This is ok, for 1 or 2 properties but what if I want to get all the properties?
4

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.

Comments

2

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.

1 Comment

That is definitely one way to do it but, the node that I delete has relationships and your solution would not be feasible there (except if I delete relationships) in which case I would need two query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.