Is it possible to delete a document from a script?

Hi,

I would like to delete the document which a script is called upon.
The use case for this is I have a list of resources in the doc, which can grow or shrink, according to their availability.
I want the doc to disappear when this list becomes empty, so when I call the script -let's name it removeResource-, it should simply delete the doc when this list becomes empty in the same transaction.
Is this possible to do via scripting? How?

Are there any extended docs in scripting?

Thanks,

You can't do it in a single call. Since atomicity seems to be your main concern, you would have to do the following:

  1. run a get operation on your document, this will in particular return a _version
  2. if the list of resources would be empty after the update then run a delete operation
  3. otherwise run an index operation that removes a resource from the list

For steps 2 and 3, it is important to specify the version so that you can be sure to replace the exact same document that you got on step 1. And in case of a version conflict, you need to start again from step 1.

See https://www.elastic.co/blog/elasticsearch-versioning-support for more information about versioning.

So there is no delete support in scripts. Are the any technical reasons for this, or just didn't yet happen? :slightly_smiling:

I will do it this way, thank you very much for the quick response!

Indeed there is no way to have a script to run some kinds of "update-or-delete" operations. I don't think there is a particular reason to it, just that the current APIs cover most use-cases and that most other use-cases can be solved with several calls to the API.

Actually, it is both possible and documented:

PUT t/t/1
{}

POST t/t/1/_update
{
  "script": "ctx.op='delete'"
}

GET t/t/1

Woops my bad. Thanks Clinton for restoring the truth.