---
type: api
title: Update a document
description: Update a document by running a script or passing a partial document.
url: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-update
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/operation/operation-update
products:
  - Elasticsearch
---

# Update a document

Availability:

## Paths

- `POST` `/{index}/_update/{id}`

- [Api key auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#apikeyauth)
- [Basic auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#basicauth)
- [Bearer auth](/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v9/authentication#bearerauth)

#### Path Parameters

- `index` (string IndexName)
  The name of the target index.
By default, the index is created automatically if it doesn't exist.
- `id` (string Id)
  A unique identifier for the document to be updated.

## Description

Update a document by running a script or passing a partial document.

If the Elasticsearch security features are enabled, you must have the `index` or `write` index privilege for the target index or index alias.

The script can update, delete, or skip modifying the document.
The API also supports passing a partial document, which is merged into the existing document.
To fully replace an existing document, use the index API.
This operation:

* Gets the document (collocated with the shard) from the index.
* Runs the specified script.
* Indexes the result.

The document must still be reindexed, but using this API removes some network roundtrips and reduces chances of version conflicts between the GET and the index operation.

The `_source` field must be enabled to use this API.
In addition to `_source`, you can access the following variables through the `ctx` map: `_index`, `_type`, `_id`, `_version`, `_routing`, and `_now` (the current timestamp).
For usage examples such as partial updates, upserts, and scripted updates, see the External documentation.

## Required authorization

* Index privileges: `write`

[More about updating a document](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/update-document)

## Query String Parameters

- `if_primary_term` (number)
  Only perform the operation if the document has this primary term.
- `if_seq_no` (number SequenceNumber)
  Only perform the operation if the document has this sequence number.
- `include_source_on_error` (boolean · default: true)
  True or false if to include the document source in the error message in case of parsing errors.
- `lang` (string · default: painless)
  The script language.
- `refresh` (enum Refresh · default: false)
  If 'true', Elasticsearch refreshes the affected shards to make this operation visible to search.
If 'wait_for', it waits for a refresh to make this operation visible to search.
If 'false', it does nothing with refreshes.
  Values: `true`, `false`, `wait_for`
- `require_alias` (boolean · default: false)
  If `true`, the destination must be an index alias.
- `retry_on_conflict` (number · default: 0)
  The number of times the operation should be retried when a conflict occurs.
- `routing` (union Routing)
  A custom value used to route operations to a specific shard.
Not allowed when `index.slice.enabled` is `true` for the target index; use `_slice` instead.
  One of: `string` or `string[]`
- `timeout` (string Duration · default: 1m)
  The period to wait for the following operations: dynamic mapping updates and waiting for active shards.
Elasticsearch waits for at least the timeout period before failing.
The actual wait time could be longer, particularly when multiple waits occur.
- `wait_for_active_shards` (WaitForActiveShards · default: 1)
  The number of copies of each shard that must be active before proceeding with the operation.
Set to 'all' or any positive integer up to the total number of shards in the index (`number_of_replicas`+1).
The default value of `1` means it waits for each primary shard to be active.
  Values: `all`, `index-setting`
- `_source` (SourceConfigParam · default: true)
  If `false`, source retrieval is turned off.
You can also specify a comma-separated list of the fields you want to retrieve.
- `_source_excludes` (union Fields)
  The source fields you want to exclude.
  One of: `Field` or `Field[]`
- `_source_includes` (union Fields)
  The source fields you want to retrieve.
  One of: `Field` or `Field[]`

## Request Body

`application/json`

- `detect_noop` (boolean · default: true) — optional
  If `true`, the `result` in the response is set to `noop` (no operation) when there are no changes to the document.
- `doc` (object) — optional
  A partial update to an existing document.
If both `doc` and `script` are specified, `doc` is ignored.
- `doc_as_upsert` (boolean · default: false) — optional
  If `true`, use the contents of 'doc' as the value of 'upsert'.
NOTE: Using ingest pipelines with `doc_as_upsert` is not supported.
- `script` (string Script) — optional
  The script to run to update the document.
- `scripted_upsert` (boolean · default: false) — optional
  If `true`, run the script whether or not the document exists.
- `_source` (SourceConfig · default: true) — optional
  If `false`, turn off source retrieval.
You can also specify a comma-separated list of the fields you want to retrieve.
- `upsert` (object) — optional
  If the document does not already exist, the contents of 'upsert' are inserted as a new document.
If the document exists, the 'script' is run.

## Response

`application/json`

- `_id` (string Id)
  The unique identifier for the added document.
- `_index` (string IndexName)
  The name of the index the document was added to.
- `_primary_term` (number)
  The primary term assigned to the document for the indexing operation.
- `result` (enum Result)
  The result of the indexing operation: `created` or `updated`.
  Values: `created`, `updated`, `deleted`, `not_found`, `noop`
- `_seq_no` (number SequenceNumber)
  The sequence number assigned to the document for the indexing operation.
Sequence numbers are used to ensure an older version of a document doesn't overwrite a newer version.
- `_shards` ({} ShardStatistics)
  Information about the replication process of the operation.
  - `failed` (number uint)
    The number of shards the operation or search attempted to run on but failed.
  - `successful` (number uint)
    The number of shards the operation or search succeeded on.
  - `total` (number uint)
    The number of shards the operation or search will run on overall.
  - `failures` ([] ShardFailure)
    - `index` (string IndexName)
    - `node` (string)
    - `reason` ({} ErrorCause)
      - `type` (string)
        The type of error
      - `reason` (union string) — nullable
        A human-readable explanation of the error, in English.
        One of: `string`
      - `stack_trace` (string)
        The server stack trace. Present only if the `error_trace=true` parameter was sent with the request.
      - `caused_by` ({} ErrorCause) — recursive
        Same fields as `reason` in `failures`
      - `root_cause` ([] ErrorCause) — recursive
        Same fields as `reason` in `failures`
      - `suppressed` ([] ErrorCause) — recursive
        Same fields as `reason` in `failures`
    - `shard` (number)
    - `status` (string)
    - `primary` (boolean)
  - `skipped` (number uint)
- `_version` (number VersionNumber)
  The document version, which is incremented each time the document is updated.
- `failure_store` (enum FailureStoreStatus)
  The role of the failure store in this document response
  Values: `not_applicable_or_unknown`, `used`, `not_enabled`, `failed`
- `forced_refresh` (boolean)
- `get` ({} InlineGet)
  - `fields` (map string to object)
  - `found` (boolean)
  - `_seq_no` (number SequenceNumber)
  - `_primary_term` (number)
  - `_routing` (string Routing)
  - `_source` (object)
## Code Examples

#### Console

```console
POST test/_update/1
{
  "script" : {
    "source": "ctx._source.counter += params.count",
    "lang": "painless",
    "params" : {
      "count" : 4
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.update({
  index: "test",
  id: 1,
  script: {
    source: "ctx._source.counter += params.count",
    lang: "painless",
    params: {
      count: 4,
    },
  },
});
```

#### Python

```python
resp = client.update(
    index="test",
    id="1",
    script={
        "source": "ctx._source.counter += params.count",
        "lang": "painless",
        "params": {
            "count": 4
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/test/_update/1" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "script": {
      "source": "ctx._source.counter \u002B= params.count",
      "lang": "painless",
      "params": {
        "count": 4
      }
    }
  }'
```

#### Java

```java
client.update(u -> u
    .id("1")
    .index("test")
    .script(s -> s
        .source(so -> so
            .scriptString("ctx._source.counter += params.count")
        )
        .params("count", JsonData.fromJson("4"))
        .lang("painless")
    )
,Void.class);
```

#### C#

```c#
var response = await client
    .UpdateAsync<MyDocument, MyDocument>(index: "test", id: "1", d1 => d1
        .Script(d2 => d2
            .Lang(ScriptLanguage.Painless)
            .Params(new Dictionary<string, object>()
            {
                { "count", 4 }
            })
            .Source("ctx._source.counter += params.count")
        )
    );
```

#### PHP

```php
$resp = $client->update([
    "index" => "test",
    "id" => "1",
    "body" => [
        "script" => [
            "source" => "ctx._source.counter += params.count",
            "lang" => "painless",
            "params" => [
                "count" => 4,
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.update(
  index: "test",
  id: "1",
  body: {
    "script": {
      "source": "ctx._source.counter += params.count",
      "lang": "painless",
      "params": {
        "count": 4
      }
    }
  }
)
```

## Response Examples

#### Detect noop updates

By default updates that don't change anything detect that they don't change anything and return `"result": "noop"`.

```json
{
   "_shards": {
        "total": 0,
        "successful": 0,
        "failed": 0
   },
   "_index": "test",
   "_id": "1",
   "_version": 2,
   "_primary_term": 1,
   "_seq_no": 1,
   "result": "noop"
}
```

