---
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/4493/api/doc/elasticsearch-serverless/operation/operation-update
resource: https://www.elastic.co/elastic/docs-builder/docs/4493/api/doc/elasticsearch-serverless/operation/operation-update
products:
  - Elasticsearch Serverless
---

# Update a document

## Paths

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

#### Path parameters

- `index` (string) — required
  The name of the target index.
By default, the index is created automatically if it doesn't exist.
- `id` (string) — required
  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.

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

## Required authorization

- Index privileges: `write`

## Authentication

- Api key: `Authorization: <value>`
  Elasticsearch APIs use key-based authentication.
  You must create an API key and use the encoded value in the request header.
  For example:
  
  
  ```
  curl -X GET "${ES_URL}/_cat/indices?v=true" \
    -H "Authorization: ApiKey ${API_KEY}"
  ```
  
  For more information about where to find API keys for the Elasticsearch endpoint (${ES_URL}) for a project, go to [Get started with Elasticsearch Serverless](https://www.elastic.co/docs/solutions/search/serverless-elasticsearch-get-started).

## Query string parameters

- `if_primary_term` (number) — optional
  Only perform the operation if the document has this primary term.
- `if_seq_no` (number) — optional
  Only perform the operation if the document has this sequence number.
- `include_source_on_error` (boolean · default: true) — optional
  True or false if to include the document source in the error message in case of parsing errors.
- `lang` (string · default: painless) — optional
  The script language.
- `refresh` (enum · default: false) — optional
  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) — optional
  If `true`, the destination must be an index alias.
- `retry_on_conflict` (number · default: 0) — optional
  The number of times the operation should be retried when a conflict occurs.
- `timeout` (string · default: 1m) — optional
  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.
- `_source` (union · default: true) — optional
  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 oneOf) — optional
  The source fields you want to exclude.
  One of: `string[]` or `string`
- `_source_includes` (union oneOf) — optional
  The source fields you want to retrieve.
  One of: `string[]` or `string`

## 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) — 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` (union · 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)
  The unique identifier for the added document.
- `_index` (string)
  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)
  The result of the indexing operation: `created` or `updated`.
  Values: `created`, `updated`, `deleted`, `not_found`, `noop`
- `_seq_no` (number)
  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` (object)
  Information about the replication process of the operation.
  - `failed` (number)
    The number of shards the operation or search attempted to run on but failed.
  - `successful` (number)
    The number of shards the operation or search succeeded on.
  - `total` (number)
    The number of shards the operation or search will run on overall.
  - `failures` (object[])
    - `index` (string)
    - `node` (string)
    - `reason` (object)
      - `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` (object) — recursive
        Same fields as `reason` in `failures`
      - `root_cause` (object[]) — recursive
        Same fields as `reason` in `failures`
      - `suppressed` (object[]) — recursive
        Same fields as `reason` in `failures`
    - `shard` (number)
    - `status` (string)
    - `primary` (boolean)
  - `skipped` (number)
- `_version` (number)
  The document version, which is incremented each time the document is updated.
- `failure_store` (enum)
  The role of the failure store in this document response
  Values: `not_applicable_or_unknown`, `used`, `not_enabled`, `failed`
- `forced_refresh` (boolean)
- `get` (object)
  - `fields` (map string to object)
  - `found` (boolean)
  - `_seq_no` (number)
  - `_primary_term` (number)
  - `_routing` (string)
  - `_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"
}
```

