---
type: api
title: Create or update a watch
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4493/api/doc/elasticsearch/v8/operation/operation-watcher-put-watch
resource: https://www.elastic.co/elastic/docs-builder/docs/4493/api/doc/elasticsearch/v8/operation/operation-watcher-put-watch
products:
  - Elasticsearch
---

# Create or update a watch


## Paths

- `POST` (also `PUT`) `/_watcher/watch/{id}`

#### Path parameters

- `id` (string) — required
  The identifier for the watch.

## Description

When a watch is registered, a new document that represents the watch is added to the `.watches` index and its trigger is immediately registered with the relevant trigger engine.
Typically for the `schedule` trigger, the scheduler is the trigger engine.

IMPORTANT: You must use Kibana or this API to create a watch.
Do not add a watch directly to the `.watches` index by using the Elasticsearch index API.
If Elasticsearch security features are enabled, do not give users write privileges on the `.watches` index.

When you add a watch you can also define its initial active state by setting the *active* parameter.

When Elasticsearch security features are enabled, your watch can index or search only on indices for which the user that stored the watch has privileges.
If the user is able to read index `a`, but not index `b`, the same will apply when the watch runs.

## Required authorization

- Cluster privileges: `manage_watcher`

## Authentication

- Api key: `Authorization: <value>`
  Elasticsearch APIs support 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}"
  ```
  
  To get API keys, use the `/_security/api_key` APIs.
- Basic: `Authorization: Basic <credentials>`
- Bearer: `Authorization: Bearer <token>`
  Elasticsearch APIs support the use of bearer tokens in the `Authorization` HTTP header to authenticate with the API.
  For examples, refer to [Token-based authentication services](https://www.elastic.co/guide/en/elasticsearch/reference/current/token-authentication-services.html)

## Query string parameters

- `active` (boolean · default: true) — optional
  The initial state of the watch.
The default value is `true`, which means the watch is active by default.
- `if_primary_term` (number) — optional
  Only update the watch if the last operation that has changed the watch has the specified primary term
- `if_seq_no` (number) — optional
  Only update the watch if the last operation that has changed the watch has the specified sequence number
- `version` (number) — optional
  Explicit version number for concurrency control

## Request body

`application/json`

- `actions` (map string to object) — optional
  The list of actions that will be run if the condition matches.
  Map values (object)
  - `action_type` (enum) — optional
    Values: `email`, `webhook`, `index`, `logging`, `slack`, `pagerduty`
  - `condition` (object) — optional
    - `always` (object) — optional
    - `array_compare` (map string to object · min properties: 1 · max properties: 1) — optional
      Map values (object)
      - `path` (string) — required
    - `compare` (map string to string to oneOf · min properties: 1 · max properties: 1) — optional
      Map values (map string to oneOf · min properties: 1 · max properties: 1)
    - `never` (object) — optional
    - `script` (object) — optional
      - `lang` (string · default: painless) — optional
      - `params` (map string to object) — optional
      - `source` (string) — optional
      - `id` (string) — optional
  - `foreach` (string) — optional
  - `max_iterations` (number) — optional
  - `name` (string) — optional
  - `throttle_period` (string) — optional
  - `throttle_period_in_millis` (number) — optional
  - `transform` (object) — optional
    - `chain` (object[]) — optional — recursive
      Same fields as `transform` in `actions`
    - `script` (object) — optional
      - `lang` (string · default: painless) — optional
      - `params` (map string to object) — optional
      - `source` (string) — optional
      - `id` (string) — optional
    - `search` (object) — optional
      - `request` (object) — required
        - `body` (object) — optional
          - `query` ({} Query) — required
            See [Query](https://www.elastic.co/elastic/docs-builder/docs/4493/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer)
        - `indices` (string[]) — optional
        - `indices_options` (object) — optional
          - `allow_no_indices` (boolean) — optional
            If false, the request returns an error if any wildcard expression, index alias, or `_all` value targets only
missing or closed indices. This behavior applies even if the request targets other open indices. For example,
a request targeting `foo*,bar*` returns an error if an index starts with `foo` but no index starts with `bar`.
          - `expand_wildcards` (string) — optional
            Type of index that wildcard patterns can match. If the request can target data streams, this argument
determines whether wildcard expressions match hidden data streams. Supports comma-separated values,
such as `open,hidden`.

Supported values include:
  - `all`: Match any data stream or index, including hidden ones.
  - `open`: Match open, non-hidden indices. Also matches any non-hidden data stream.
  - `closed`: Match closed, non-hidden indices. Also matches any non-hidden data stream. Data streams cannot be closed.
  - `hidden`: Match hidden data streams and hidden indices. Must be combined with `open`, `closed`, or `both`.
  - `none`: Wildcard expressions are not accepted.
            Values: `all`, `open`, `closed`, `hidden`, `none`
          - `ignore_unavailable` (boolean · default: false) — optional
            If true, missing or closed indices are not included in the response.
          - `ignore_throttled` (boolean · default: true) — optional
            If true, concrete, expanded or aliased indices are ignored when frozen.
        - `search_type` (enum) — optional
          

Supported values include:
  - `query_then_fetch`: Documents are scored using local term and document frequencies for the shard. This is usually faster but less accurate.
  - `dfs_query_then_fetch`: Documents are scored using global term and document frequencies across all shards. This is usually slower but more accurate.
          Values: `query_then_fetch`, `dfs_query_then_fetch`
        - `template` (object) — optional
          - `explain` (boolean · default: false) — optional
          - `id` (string) — optional
            ID of the search template to use. If no source is specified,
this parameter is required.
          - `params` (map string to object) — optional
          - `profile` (boolean · default: false) — optional
          - `source` (string) — optional
            An inline search template. Supports the same parameters as the search API's
request body. Also supports Mustache variables. If no id is specified, this
parameter is required.
        - `rest_total_hits_as_int` (boolean) — optional
      - `timeout` (string) — required
  - `index` (object) — optional
    - `index` (string) — required
    - `doc_id` (string) — optional
    - `refresh` (enum) — optional
      Values: `true`, `false`, `wait_for`
    - `op_type` (enum · default: index) — optional
      

Supported values include:
  - `index`: Overwrite any documents that already exist.
  - `create`: Only index documents that do not already exist.
      Values: `index`, `create`
    - `timeout` (string · default: 60s) — optional
    - `execution_time_field` (string) — optional
  - `logging` (object) — optional
    - `level` (string) — optional
    - `text` (string) — required
    - `category` (string) — optional
  - `email` (object) — optional
    - `id` (string) — optional
    - `bcc` (union string | string[]) — optional
    - `body` (object) — optional
      - `html` (string) — optional
      - `text` (string) — optional
    - `cc` (union string | string[]) — optional
    - `from` (string) — optional
    - `priority` (enum) — optional
      Values: `lowest`, `low`, `normal`, `high`, `highest`
    - `reply_to` (union string | string[]) — optional
    - `sent_date` (union) — optional
    - `subject` (string) — required
    - `to` (union string | string[]) — required
    - `attachments` (map string to object) — optional
      Map values (object · min properties: 1 · max properties: 1)
      - `http` (object) — optional
        - `content_type` (string) — optional
        - `inline` (boolean) — optional
        - `request` (object) — optional
          - `auth` (object) — optional
            - `basic` (object) — required
              - `password` (string) — required
              - `username` (string) — required
          - `body` (string) — optional
          - `connection_timeout` (string) — optional
          - `headers` (map string to string) — optional
          - `host` (string) — optional
          - `method` (enum) — optional
            Values: `head`, `get`, `post`, `put`, `delete`
          - `params` (map string to string) — optional
          - `path` (string) — optional
          - `port` (number) — optional
          - `proxy` (object) — optional
            - `host` (string) — required
            - `port` (number) — required
          - `read_timeout` (string) — optional
          - `scheme` (enum) — optional
            Values: `http`, `https`
          - `url` (string) — optional
      - `reporting` (object) — optional
        - `url` (string) — required
        - `inline` (boolean) — optional
        - `retries` (number · default: 40) — optional
        - `interval` (string · default: 15s) — optional
        - `request` (object) — optional
          Same fields as `request` in `http`
      - `data` (object) — optional
        - `format` (enum) — optional
          Values: `json`, `yaml`
  - `pagerduty` (object) — optional
    - `account` (string) — optional
    - `attach_payload` (boolean) — required
    - `client` (string) — optional
    - `client_url` (string) — optional
    - `contexts` (object[]) — optional
      - `href` (string) — optional
      - `src` (string) — optional
      - `type` (enum) — required
        Values: `link`, `image`
    - `description` (string) — required
    - `event_type` (enum · default: trigger) — optional
      Values: `trigger`, `resolve`, `acknowledge`
    - `incident_key` (string) — required
    - `proxy` (object) — optional
      - `host` (string) — optional
      - `port` (number) — optional
  - `slack` (object) — optional
    - `account` (string) — optional
    - `message` (object) — required
      - `attachments` (object[]) — required
        - `author_icon` (string) — optional
        - `author_link` (string) — optional
        - `author_name` (string) — required
        - `color` (string) — optional
        - `fallback` (string) — optional
        - `fields` (object[]) — optional
          - `short` (boolean) — required
          - `title` (string) — required
          - `value` (string) — required
        - `footer` (string) — optional
        - `footer_icon` (string) — optional
        - `image_url` (string) — optional
        - `pretext` (string) — optional
        - `text` (string) — optional
        - `thumb_url` (string) — optional
        - `title` (string) — required
        - `title_link` (string) — optional
        - `ts` (number) — optional
      - `dynamic_attachments` (object) — optional
        - `attachment_template` (object) — required
          Same fields as `attachments` in `message`
        - `list_path` (string) — required
      - `from` (string) — required
      - `icon` (string) — optional
      - `text` (string) — required
      - `to` (string[]) — required
  - `webhook` (object) — optional
    - `auth` (object) — optional
      - `basic` (object) — required
        - `password` (string) — required
        - `username` (string) — required
    - `body` (string) — optional
    - `connection_timeout` (string) — optional
    - `headers` (map string to string) — optional
    - `host` (string) — optional
    - `method` (enum) — optional
      Values: `head`, `get`, `post`, `put`, `delete`
    - `params` (map string to string) — optional
    - `path` (string) — optional
    - `port` (number) — optional
    - `proxy` (object) — optional
      - `host` (string) — required
      - `port` (number) — required
    - `read_timeout` (string) — optional
    - `scheme` (enum) — optional
      Values: `http`, `https`
    - `url` (string) — optional
- `condition` (object) — optional
  The condition that defines if the actions should be run.
  Same fields as `condition` in `actions`
- `input` (object) — optional
  The input that defines the input that loads the data for the watch.
  - `chain` (object) — optional
    - `inputs` (string to object[]) — required — recursive
      Same fields as `input`
  - `http` (object) — optional
    - `extract` (string[]) — optional
    - `request` (object) — optional
      Same fields as `request` in `http`
    - `response_content_type` (enum) — optional
      Values: `json`, `yaml`, `text`
  - `search` (object) — optional
    - `extract` (string[]) — optional
    - `request` (object) — required
      Same fields as `request` in `search`
    - `timeout` (string) — optional
  - `simple` (map string to object) — optional
- `metadata` (object) — optional
  Metadata JSON that will be copied into the history entries.
- `throttle_period` (string) — optional
  The minimum time between actions being run.
The default is 5 seconds.
This default can be changed in the config file with the setting `xpack.watcher.throttle.period.default_period`.
If both this value and the `throttle_period_in_millis` parameter are specified, Watcher uses the last parameter included in the request.
- `throttle_period_in_millis` (number) — optional
  Minimum time in milliseconds between actions being run. Defaults to 5000. If both this value and the throttle_period parameter are specified, Watcher uses the last parameter included in the request.
- `transform` (object) — optional
  The transform that processes the watch payload to prepare it for the watch actions.
  Same fields as `transform` in `actions`
- `trigger` (object) — optional
  The trigger that defines when the watch should run.
  - `schedule` (object) — optional
    - `timezone` (string) — optional
    - `cron` (string) — optional
    - `daily` (object) — optional
      - `at` (union oneOf[]) — required
        - **string**
        - **{ hour, minute }**
          - `hour` (number[]) — required
          - `minute` (number[]) — required
    - `hourly` (object) — optional
      - `minute` (number[]) — required
    - `interval` (string) — optional
    - `monthly` (union oneOf) — optional
      `object` or `object[]`
      - `at` (string[]) — required
      - `on` (number[]) — required
    - `weekly` (union oneOf) — optional
      `object` or `object[]`
      - `at` (string[]) — required
      - `on` (enum[]) — required
        Values: `sunday`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`
    - `yearly` (union oneOf) — optional
      `object` or `object[]`
      - `at` (string[]) — required
      - `int` (enum[]) — required
        Values: `january`, `february`, `march`, `april`, `may`, `june`, `july`, `august`, `september`, `october`, `november`, `december`
      - `on` (number[]) — required

## Response

`application/json`

- `created` (boolean)
- `_id` (string)
- `_primary_term` (number)
- `_seq_no` (number)
- `_version` (number)
## Code examples

#### Console

```console
POST _watcher/watch/my-watch
{
  "trigger" : {
    "schedule" : { "cron" : "0 0/1 * * * ?" }
  },
  "input" : {
    "search" : {
      "request" : {
        "indices" : [
          "logstash*"
        ],
        "body" : {
          "query" : {
            "bool" : {
              "must" : {
                "match": {
                  "response": 404
                }
              },
              "filter" : {
                "range": {
                  "@timestamp": {
                    "from": "{{ctx.trigger.scheduled_time}}||-5m",
                    "to": "{{ctx.trigger.triggered_time}}"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "condition" : {
    "compare" : { "ctx.payload.hits.total" : { "gt" : 0 }}
  },
  "actions" : {
    "email_admin" : {
      "email" : {
        "to" : "admin@domain.host.com",
        "subject" : "404 recently encountered"
      }
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.watcher.putWatch({
  id: "my-watch",
  trigger: {
    schedule: {
      cron: "0 0/1 * * * ?",
    },
  },
  input: {
    search: {
      request: {
        indices: ["logstash*"],
        body: {
          query: {
            bool: {
              must: {
                match: {
                  response: 404,
                },
              },
              filter: {
                range: {
                  "@timestamp": {
                    from: "{{ctx.trigger.scheduled_time}}||-5m",
                    to: "{{ctx.trigger.triggered_time}}",
                  },
                },
              },
            },
          },
        },
      },
    },
  },
  condition: {
    compare: {
      "ctx.payload.hits.total": {
        gt: 0,
      },
    },
  },
  actions: {
    email_admin: {
      email: {
        to: "admin@domain.host.com",
        subject: "404 recently encountered",
      },
    },
  },
});
```

#### Python

```python
resp = client.watcher.put_watch(
    id="my-watch",
    trigger={
        "schedule": {
            "cron": "0 0/1 * * * ?"
        }
    },
    input={
        "search": {
            "request": {
                "indices": [
                    "logstash*"
                ],
                "body": {
                    "query": {
                        "bool": {
                            "must": {
                                "match": {
                                    "response": 404
                                }
                            },
                            "filter": {
                                "range": {
                                    "@timestamp": {
                                        "from": "{{ctx.trigger.scheduled_time}}||-5m",
                                        "to": "{{ctx.trigger.triggered_time}}"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    condition={
        "compare": {
            "ctx.payload.hits.total": {
                "gt": 0
            }
        }
    },
    actions={
        "email_admin": {
            "email": {
                "to": "admin@domain.host.com",
                "subject": "404 recently encountered"
            }
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_watcher/watch/my-watch" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "trigger": {
      "schedule": {
        "cron": "0 0/1 * * * ?"
      }
    },
    "input": {
      "search": {
        "request": {
          "indices": [
            "logstash*"
          ],
          "body": {
            "query": {
              "bool": {
                "must": {
                  "match": {
                    "response": 404
                  }
                },
                "filter": {
                  "range": {
                    "@timestamp": {
                      "from": "{{ctx.trigger.scheduled_time}}||-5m",
                      "to": "{{ctx.trigger.triggered_time}}"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "condition": {
      "compare": {
        "ctx.payload.hits.total": {
          "gt": 0
        }
      }
    },
    "actions": {
      "email_admin": {
        "email": {
          "to": "admin@domain.host.com",
          "subject": "404 recently encountered"
        }
      }
    }
  }'
```

#### Java

```java
client.watcher().putWatch(p -> p
    .actions("email_admin", a -> a
        .email(e -> e
            .subject("404 recently encountered")
            .to("admin@domain.host.com")
        )
    )
    .condition(c -> c
        .compare(NamedValue.of("ctx.payload.hits.total",Pair.of(ConditionOp.Gt,FieldValue.of(0))))
    )
    .id("my-watch")
    .input(i -> i
        .search(s -> s
            .request(r -> r
                .body(b -> b
                    .query(q -> q
                        .bool(bo -> bo
                            .filter(f -> f
                                .range(ra -> ra
                                    .untyped(u -> u
                                        .field("@timestamp")
                                    )
                                )
                            )
                            .must(m -> m
                                .match(ma -> ma
                                    .field("response")
                                    .query(FieldValue.of(404))
                                )
                            )
                        )
                    )
                )
                .indices("logstash*")
            )
        )
    )
    .trigger(t -> t
        .schedule(sc -> sc
            .cron("0 0/1 * * * ?")
        )
    )
);
```

#### PHP

```php
$resp = $client->watcher()->putWatch([
    "id" => "my-watch",
    "body" => [
        "trigger" => [
            "schedule" => [
                "cron" => "0 0/1 * * * ?",
            ],
        ],
        "input" => [
            "search" => [
                "request" => [
                    "indices" => array(
                        "logstash*",
                    ),
                    "body" => [
                        "query" => [
                            "bool" => [
                                "must" => [
                                    "match" => [
                                        "response" => 404,
                                    ],
                                ],
                                "filter" => [
                                    "range" => [
                                        "@timestamp" => [
                                            "from" => "{{ctx.trigger.scheduled_time}}||-5m",
                                            "to" => "{{ctx.trigger.triggered_time}}",
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ],
        "condition" => [
            "compare" => [
                "ctx.payload.hits.total" => [
                    "gt" => 0,
                ],
            ],
        ],
        "actions" => [
            "email_admin" => [
                "email" => [
                    "to" => "admin@domain.host.com",
                    "subject" => "404 recently encountered",
                ],
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.watcher.put_watch(
  id: "my-watch",
  body: {
    "trigger": {
      "schedule": {
        "cron": "0 0/1 * * * ?"
      }
    },
    "input": {
      "search": {
        "request": {
          "indices": [
            "logstash*"
          ],
          "body": {
            "query": {
              "bool": {
                "must": {
                  "match": {
                    "response": 404
                  }
                },
                "filter": {
                  "range": {
                    "@timestamp": {
                      "from": "{{ctx.trigger.scheduled_time}}||-5m",
                      "to": "{{ctx.trigger.triggered_time}}"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "condition": {
      "compare": {
        "ctx.payload.hits.total": {
          "gt": 0
        }
      }
    },
    "actions": {
      "email_admin": {
        "email": {
          "to": "admin@domain.host.com",
          "subject": "404 recently encountered"
        }
      }
    }
  }
)
```

