Scripted updates - truongductri01/elasticSearch-tutorial GitHub Wiki

Scripted updates

In the previous tutorial, we set an in_stock value of the product with id 100 to 3 manually. Now that we want to decrease its value by 1 automatically regardless of the current value.

We can achieve this with scripted updates

Here is the script:

POST /<index_name>/_update/<doc_id>
{
  "script": {
    "source": "ctx._source.in_stock--"
  }
}

ctx is a variable stand for context. _source will return the data of the document and -- will decrease the value of the attribute listed

Assignment query:

POST /<index_name>/_update/<doc_id>
{
  "script": {
    "source": "ctx._source.in_stock = 10"
  }
}

Dynamic argument script:

POST /<index_name>/_update/<doc_id>
{
  "script": {
    "source": "ctx._source.in_stock -= params.quantity",
    "params": {
      "quantity": 4
    }
  }
}

can we extract the argument from the API instead?

If you want to write a multiple line code, use """ (triple double quotes) instead of just a single double quote. Example:

POST /products/_update/100
{
  "script": {
    "source": """
      if (ctx._source.in_stock <= 1) {
        ctx.op = 'delete';
      }
      ctx._source.in_stock--;
    """
  }
}```

With `ctx.op = 'delete';` will remove the document completely from the idex
⚠️ **GitHub.com Fallback** ⚠️