﻿---
title: Update by query API examples
description: The Update by query API updates all documents that match a specified query, enabling bulk modification of the document source or metadata via a script...
url: https://www.elastic.co/elastic/docs-builder/docs/2831/reference/elasticsearch/rest-apis/update-by-query-api
products:
  - Elasticsearch
applies_to:
  - Elastic Stack: Generally available
---

# Update by query API examples
The [Update by query API](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update-by-query) updates all documents that match a specified query, enabling bulk modification of the document source or metadata via a script.
You can learn how to:
- [Run basic update-by-query operations](#run-basic-updates)
- [Modify documents using scripts or ingest pipelines](#update-the-document)
- [Throttle update operations](#change-throttling-for-a-request)
- [Parallelize updates using manual slicing](#slice-manually)
- [Automate slicing for better performance](#use-automatic-slicing)
- [Apply mapping changes to existing documents](#pick-up-a-new-property)


## Run basic updates

The simplest usage of `_update_by_query` just performs an update on every document in the data stream or index without changing the source. This is useful to [pick up a new property](#pick-up-a-new-property) or some other online mapping change.
To update selected documents, specify a query in the request body:
```json

{
  "query": { <1>
    "term": {
      "user.id": "kimchy"
    }
  }
}
```


### Target multiple indices

Update documents in multiple data streams or indices:
```json
```


### Filter by routing

Limit the update by query operation to shards that a particular routing value:
```json
```


### Change batch size

By default update by query uses scroll batches of 1000. You can change the batch size with the `scroll_size` parameter:
```json
```


## Update the document

Update a document using a unique attribute:
```json

{
  "query": {
    "term": {
      "user.id": "kimchy"
    }
  },
  "max_docs": 1
}
```


### Update the document source

Update by query supports scripts to update the document source. For example, the following request increments the `count` field for all documents with a `user.id` of `kimchy` in `my-index-000001`:
```json

{
  "script": {
    "source": "ctx._source.count++",
    "lang": "painless"
  },
  "query": {
    "term": {
      "user.id": "kimchy"
    }
  }
}
```

Note that `conflicts=proceed` is not specified in this example. In this case, a version conflict should halt the process so you can handle the failure.
As with the [Update API](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update), you can set `ctx.op` to change the operation that is performed:
<definitions>
  <definition term="noop">
    Set `ctx.op = "noop"` if your script decides that it doesn't have to make any changes.
    The update by query operation skips updating the document and increments the  `noop` counter.
  </definition>
  <definition term="delete">
    Set `ctx.op = "delete"` if your script decides that the document should be deleted.
    The update by query operation deletes the document and increments the  `deleted` counter.
  </definition>
</definitions>

Update by query only supports `index`, `noop`, and `delete`. Setting `ctx.op` to anything else is an error. Setting any other field in `ctx` is an error.
This API only enables you to modify the source of matching documents, you cannot move them.

### Update documents using an ingest pipeline

Update by query can use the [ingest pipelines](https://docs-v3-preview.elastic.dev/elastic/docs-builder/docs/2831/manage-data/ingest/transform-enrich/ingest-pipelines) feature by specifying a `pipeline`:
```json

{
  "description" : "sets foo",
  "processors" : [ {
      "set" : {
        "field": "foo",
        "value": "bar"
      }
  } ]
}
```


### Get the status of update by query operations

You can fetch the status of all running update by query requests with the [Task API](https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-tasks):
```json
```

The responses looks like:
```json
{
  "nodes" : {
    "r1A2WoRbTwKZ516z6NEs5A" : {
      "name" : "r1A2WoR",
      "transport_address" : "127.0.0.1:9300",
      "host" : "127.0.0.1",
      "ip" : "127.0.0.1:9300",
      "attributes" : {
        "testattr" : "test",
        "portsfile" : "true"
      },
      "tasks" : {
        "r1A2WoRbTwKZ516z6NEs5A:36619" : {
          "node" : "r1A2WoRbTwKZ516z6NEs5A",
          "id" : 36619,
          "type" : "transport",
          "action" : "indices:data/write/update/byquery",
          "status" : {    
            "total" : 6154,
            "updated" : 3500,
            "created" : 0,
            "deleted" : 0,
            "batches" : 4,
            "version_conflicts" : 0,
            "noops" : 0,
            "retries": {
              "bulk": 0,
              "search": 0
            },
            "throttled_millis": 0
          },
          "description" : ""
        }
      }
    }
  }
}
```

With the task id you can look up the task directly. The following example retrieves information about task `r1A2WoRbTwKZ516z6NEs5A:36619`:
```json
```

The advantage of this API is that it integrates with `wait_for_completion=false` to transparently return the status of completed tasks. If the task is completed and `wait_for_completion=false` was set on it, then it'll come back with a `results` or an `error` field. The cost of this feature is the document that `wait_for_completion=false` creates at `.tasks/task/${taskId}`. It is up to you to delete that document.

### Cancel an update by query operation

Any update by query can be cancelled using the [Cancel API](https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-tasks):
```json
```

The task ID can be found using the [Task API](https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-tasks).
Cancellation should happen quickly but might take a few seconds. The task status API above will continue to list the update by query task until this task checks that it has been cancelled and terminates itself.

## Change throttling for a request

The value of `requests_per_second` can be changed on a running update by query using the `_rethrottle` API:
```json
```

The task ID can be found using the [Task API](https://www.elastic.co/docs/api/doc/elasticsearch/group/endpoint-tasks).
Just like when setting it on the `_update_by_query` API, `requests_per_second` can be either `-1` to disable throttling or any decimal number like `1.7` or `12` to throttle to that level. Rethrottling that speeds up the query takes effect immediately, but rethrotting that slows down the query will take effect after completing the current batch. This prevents scroll timeouts.

## Slice manually

Slice an update by query manually by providing a slice id and total number of slices to each request:
```json

{
  "slice": {
    "id": 0,
    "max": 2
  },
  "script": {
    "source": "ctx._source['extra'] = 'test'"
  }
}

{
  "slice": {
    "id": 1,
    "max": 2
  },
  "script": {
    "source": "ctx._source['extra'] = 'test'"
  }
}
```

Which you can verify works with:
```json
```

Which results in a sensible `total` like this one:
```json
{
  "hits": {
    "total": {
        "value": 120,
        "relation": "eq"
    }
  }
}
```


## Use automatic slicing

You can also let update by query automatically parallelize using [slice-scroll](/elastic/docs-builder/docs/2831/reference/elasticsearch/rest-apis/paginate-search-results#slice-scroll) to slice on `_id`. Use `slices` to specify the number of slices to use:
```json

{
  "script": {
    "source": "ctx._source['extra'] = 'test'"
  }
}
```

Which you also can verify works with:
```json
```

Which results in a sensible `total` like this one:
```json
{
  "hits": {
    "total": {
        "value": 120,
        "relation": "eq"
    }
  }
}
```

Setting `slices` to `auto` will let Elasticsearch choose the number of slices to use. This setting will use one slice per shard, up to a certain limit. If there are multiple source data streams or indices, it will choose the number of slices based on the index or backing index with the smallest number of shards.
Adding `slices` to `_update_by_query` just automates the manual process used in the section above, creating sub-requests which means it has some quirks:
- You can see these requests in the [Tasks APIs](https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-update-by-query). These sub-requests are "child" tasks of the task for the request with `slices`.
- Fetching the status of the task for the request with `slices` only contains the status of completed slices.
- These sub-requests are individually addressable for things like cancellation and rethrottling.
- Rethrottling the request with `slices` will rethrottle the unfinished sub-request proportionally.
- Canceling the request with `slices` will cancel each sub-request.
- Due to the nature of `slices` each sub-request won't get a perfectly even portion of the documents. All documents will be addressed, but some slices may be larger than others. Expect larger slices to have a more even distribution.
- Parameters like `requests_per_second` and `max_docs` on a request with `slices` are distributed proportionally to each sub-request. Combine that with the point above about distribution being uneven and you should conclude that using `max_docs` with `slices` might not result in exactly `max_docs` documents being updated.
- Each sub-request gets a slightly different snapshot of the source data stream or index though these are all taken at approximately the same time.


## Pick up a new property

Say you created an index without dynamic mapping, filled it with data, and then added a mapping value to pick up more fields from the data:
```json

{
  "mappings": {
    "dynamic": false,   <1>
    "properties": {
      "text": {"type": "text"}
    }
  }
}


{
  "text": "words words",
  "flag": "bar"
}

{
  "text": "words words",
  "flag": "foo"
}

{
  "properties": {
    "text": {"type": "text"},
    "flag": {"type": "text", "analyzer": "keyword"}
  }
}
```

Searching for the data won't find anything:
```json

{
  "query": {
    "match": {
      "flag": "foo"
    }
  }
}
```

```json
{
  "hits" : {
    "total": {
        "value": 0,
        "relation": "eq"
    }
  }
}
```

But you can issue an `_update_by_query` request to pick up the new mapping:
```json


{
  "query": {
    "match": {
      "flag": "foo"
    }
  }
}
```

```json
{
  "hits" : {
    "total": {
        "value": 1,
        "relation": "eq"
    }
  }
}
```

You can do the exact same thing when adding a field to a multifield.