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

Community
  • 1
  • 1
Raf
  • 7,505
  • 1
  • 42
  • 59

3 Answers3

11

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.

Community
  • 1
  • 1
William Lyon
  • 8,371
  • 1
  • 17
  • 22
  • 2
    Thank you William, exactly what I was looking for, though I had to change the query to add **j** after WITH keyword. – Raf Dec 26 '15 at 22:19
  • 2
    This is ok, for 1 or 2 properties but what if I want to get all the properties? – Dev Gaud Apr 14 '20 at 07:44
3

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.

Dev Gaud
  • 676
  • 6
  • 10
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.

FrobberOfBits
  • 17,634
  • 4
  • 52
  • 86
  • 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. – Raf Dec 26 '15 at 22:21