---
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/4371/api/doc/elasticsearch/v8/operation/operation-watcher-put-watch
resource: https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/operation/operation-watcher-put-watch
products:
  - Elasticsearch
---

# Create or update a watch


Availability:

## Paths

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

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

#### Path Parameters

- `id` (string Id)
  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`

## Query String Parameters

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

## Request Body

`application/json`

- `actions` (map string to Action) — optional
  The list of actions that will be run if the condition matches.
  Map values ({} Action)
  - `action_type` (enum ActionType) — optional
    Values: `email`, `webhook`, `index`, `logging`, `slack`, `pagerduty`
  - `condition` ({} ConditionContainer) — optional
    - `always` (AlwaysCondition) — optional
    - `array_compare` (map string to ArrayCompareCondition) — optional
      Map values ({} ArrayCompareCondition)
      - `path` (string) — required
    - `compare` (map string to string to FieldValue) — optional
    - `never` (NeverCondition) — optional
    - `script` ({} ScriptCondition) — 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 Name) — optional
  - `throttle_period` (string Duration) — optional
  - `throttle_period_in_millis` (DurationValueUnitMillis) — optional
  - `transform` ({} TransformContainer) — optional
    - `chain` ([] TransformContainer) — optional — recursive
      Same fields as `transform` in `actions`
    - `script` ({} ScriptTransform) — optional
      - `lang` (string · default: painless) — optional
      - `params` (map string to object) — optional
      - `source` (string) — optional
      - `id` (string) — optional
    - `search` ({} SearchTransform) — optional
      - `request` ({} SearchInputRequestDefinition) — required
        - `body` ({} SearchInputRequestBody) — optional
          - `query` ({} QueryContainer) — required
            See [QueryContainer](https://www.elastic.co/elastic/docs-builder/docs/4371/api/doc/elasticsearch/v8/types/_types-query_dsl-querycontainer)
        - `indices` ([] string IndexName) — optional
        - `indices_options` ({} IndicesOptions) — 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 ExpandWildcards) — 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 SearchType) — 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` ({} SearchTemplateRequestBody) — optional
          - `explain` (boolean · default: false) — optional
          - `id` (string Id) — 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 Duration) — required
  - `index` ({} IndexAction) — optional
    - `index` (string IndexName) — required
    - `doc_id` (string Id) — optional
    - `refresh` (enum Refresh) — optional
      Values: `true`, `false`, `wait_for`
    - `op_type` (enum OpType · 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 Duration · default: 60s) — optional
    - `execution_time_field` (string Field) — optional
  - `logging` ({} LoggingAction) — optional
    - `level` (string) — optional
    - `text` (string) — required
    - `category` (string) — optional
  - `email` ({} EmailAction) — optional
    - `id` (string Id) — optional
    - `bcc` (union string | [] string) — optional
    - `body` ({} EmailBody) — optional
      - `html` (string) — optional
      - `text` (string) — optional
    - `cc` (union string | [] string) — optional
    - `from` (string) — optional
    - `priority` (enum EmailPriority) — optional
      Values: `lowest`, `low`, `normal`, `high`, `highest`
    - `reply_to` (union string | [] string) — optional
    - `sent_date` (DateTime) — optional
    - `subject` (string) — required
    - `to` (union string | [] string) — required
    - `attachments` (map string to EmailAttachmentContainer) — optional
      Map values ({} EmailAttachmentContainer)
      - `http` ({} HttpEmailAttachment) — optional
        - `content_type` (string) — optional
        - `inline` (boolean) — optional
        - `request` ({} HttpInputRequestDefinition) — optional
          - `auth` ({} HttpInputAuthentication) — optional
            - `basic` ({} HttpInputBasicAuthentication) — required
              - `password` (string) — required
              - `username` (string) — required
          - `body` (string) — optional
          - `connection_timeout` (string Duration) — optional
          - `headers` (map string to string) — optional
          - `host` (string) — optional
          - `method` (enum HttpInputMethod) — optional
            Values: `head`, `get`, `post`, `put`, `delete`
          - `params` (map string to string) — optional
          - `path` (string) — optional
          - `port` (number uint) — optional
          - `proxy` ({} HttpInputProxy) — optional
            - `host` (string) — required
            - `port` (number uint) — required
          - `read_timeout` (string Duration) — optional
          - `scheme` (enum ConnectionScheme) — optional
            Values: `http`, `https`
          - `url` (string) — optional
      - `reporting` ({} ReportingEmailAttachment) — optional
        - `url` (string) — required
        - `inline` (boolean) — optional
        - `retries` (number · default: 40) — optional
        - `interval` (string Duration · default: 15s) — optional
        - `request` ({} HttpInputRequestDefinition) — optional
          Same fields as `request` in `http`
      - `data` ({} DataEmailAttachment) — optional
        - `format` (enum DataAttachmentFormat) — optional
          Values: `json`, `yaml`
  - `pagerduty` ({} PagerDutyAction) — optional
    - `account` (string) — optional
    - `attach_payload` (boolean) — required
    - `client` (string) — optional
    - `client_url` (string) — optional
    - `contexts` ([] PagerDutyContext) — optional
      - `href` (string) — optional
      - `src` (string) — optional
      - `type` (enum PagerDutyContextType) — required
        Values: `link`, `image`
    - `description` (string) — required
    - `event_type` (enum PagerDutyEventType · default: trigger) — optional
      Values: `trigger`, `resolve`, `acknowledge`
    - `incident_key` (string) — required
    - `proxy` ({} PagerDutyEventProxy) — optional
      - `host` (string) — optional
      - `port` (number) — optional
  - `slack` ({} SlackAction) — optional
    - `account` (string) — optional
    - `message` ({} SlackMessage) — required
      - `attachments` ([] SlackAttachment) — required
        - `author_icon` (string) — optional
        - `author_link` (string) — optional
        - `author_name` (string) — required
        - `color` (string) — optional
        - `fallback` (string) — optional
        - `fields` ([] SlackAttachmentField) — 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` (EpochTimeUnitSeconds) — optional
      - `dynamic_attachments` ({} SlackDynamicAttachment) — optional
        - `attachment_template` ({} SlackAttachment) — required
          Same fields as `attachments` in `message`
        - `list_path` (string) — required
      - `from` (string) — required
      - `icon` (string) — optional
      - `text` (string) — required
      - `to` ([] string) — required
  - `webhook` ({} WebhookAction) — optional
    - `auth` ({} HttpInputAuthentication) — optional
      - `basic` ({} HttpInputBasicAuthentication) — required
        - `password` (string) — required
        - `username` (string) — required
    - `body` (string) — optional
    - `connection_timeout` (string Duration) — optional
    - `headers` (map string to string) — optional
    - `host` (string) — optional
    - `method` (enum HttpInputMethod) — optional
      Values: `head`, `get`, `post`, `put`, `delete`
    - `params` (map string to string) — optional
    - `path` (string) — optional
    - `port` (number uint) — optional
    - `proxy` ({} HttpInputProxy) — optional
      - `host` (string) — required
      - `port` (number uint) — required
    - `read_timeout` (string Duration) — optional
    - `scheme` (enum ConnectionScheme) — optional
      Values: `http`, `https`
    - `url` (string) — optional
- `condition` ({} ConditionContainer) — optional
  The condition that defines if the actions should be run.
  Same fields as `condition` in `actions`
- `input` ({} InputContainer) — optional
  The input that defines the input that loads the data for the watch.
  - `chain` ({} ChainInput) — optional
    - `inputs` ([] string to InputContainer) — required — recursive
      Same fields as `input`
  - `http` ({} HttpInput) — optional
    - `extract` ([] string) — optional
    - `request` ({} HttpInputRequestDefinition) — optional
      Same fields as `request` in `http`
    - `response_content_type` (enum ResponseContentType) — optional
      Values: `json`, `yaml`, `text`
  - `search` ({} SearchInput) — optional
    - `extract` ([] string) — optional
    - `request` ({} SearchInputRequestDefinition) — required
      Same fields as `request` in `search`
    - `timeout` (string Duration) — optional
  - `simple` (map string to object) — optional
- `metadata` (Metadata) — optional
  Metadata JSON that will be copied into the history entries.
- `throttle_period` (string Duration) — 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` (DurationValueUnitMillis) — 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` ({} TransformContainer) — optional
  The transform that processes the watch payload to prepare it for the watch actions.
  Same fields as `transform` in `actions`
- `trigger` ({} TriggerContainer) — optional
  The trigger that defines when the watch should run.
  - `schedule` ({} ScheduleContainer) — optional
    - `timezone` (string) — optional
    - `cron` (string) — optional
    - `daily` ({} DailySchedule) — optional
      - `at` ([] union ScheduleTimeOfDay) — required
        - **string**
        - **HourAndMinute**
          - `hour` ([] number) — required
          - `minute` ([] number) — required
    - `hourly` ({} HourlySchedule) — optional
      - `minute` ([] number) — required
    - `interval` (string Duration) — optional
    - `monthly` (union oneOf) — optional
      `TimeOfMonth` or `TimeOfMonth[]`
      - `at` ([] string) — required
      - `on` ([] number) — required
    - `weekly` (union oneOf) — optional
      `TimeOfWeek` or `TimeOfWeek[]`
      - `at` ([] string) — required
      - `on` ([] enum Day) — required
        Values: `sunday`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`
    - `yearly` (union oneOf) — optional
      `TimeOfYear` or `TimeOfYear[]`
      - `at` ([] string) — required
      - `int` ([] enum Month) — required
        Values: `january`, `february`, `march`, `april`, `may`, `june`, `july`, `august`, `september`, `october`, `november`, `december`
      - `on` ([] number) — required

## Response

`application/json`

- `created` (boolean)
- `_id` (string Id)
- `_primary_term` (number)
- `_seq_no` (number SequenceNumber)
- `_version` (number VersionNumber)
## 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"
        }
      }
    }
  }
)
```

