---
type: api
title: Run a script
description: **All methods and paths for this operation:**
url: https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v9/operation/operation-scripts-painless-execute
resource: https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v9/operation/operation-scripts-painless-execute
products:
  - Elasticsearch
---

# Run a script

Authentication: required

Availability: Experimental since 6.3

## Paths

- `POST` (also `GET`) `/_scripts/painless/_execute`

## Description

Runs a script and returns a result.
Use this API to build and test scripts, such as when defining a script for a runtime field.
This API requires very few dependencies and is especially useful if you don't have permissions to write documents on a cluster.

The API uses several _contexts_, which control how scripts are run, what variables are available at runtime, and what the return type is.

Each context requires a script, but additional parameters depend on the context you're using for that script.

## Request body

`application/json`

- `context` (enum · default: painless_test) — optional
  The context that the script should run in.
NOTE: Result ordering in the field contexts is not guaranteed.

Supported values include:
  - `painless_test`: The default context if no other context is specified.
  - `filter`: Treats scripts as if they were run inside a script query.
  - `score`: Treats scripts as if they were run inside a `script_score` function in a `function_score` query.
  - `boolean_field`: The context for boolean fields. The script returns a `true` or `false` response.
  - `date_field`: The context for date fields. `emit` takes a long value and the script returns a sorted list of dates.
  - `double_field`: The context for double numeric fields. The script returns a sorted list of double values.
  - `geo_point_field`: The context for geo-point fields. `emit` takes two double parameters, the latitude and longitude values, and the script returns an object in GeoJSON format containing the coordinates for the geo point.
  - `ip_field`: The context for `ip` fields. The script returns a sorted list of IP addresses.
  - `keyword_field`: The context for keyword fields. The script returns a sorted list of string values.
  - `long_field`: The context for long numeric fields. The script returns a sorted list of long values.
  - `composite_field`: The context for composite runtime fields. The script returns a map of values.
  Values: `painless_test`, `filter`, `score`, `boolean_field`, `date_field`, `double_field`, `geo_point_field`, `ip_field`, `keyword_field`, `long_field`, `composite_field`
- `context_setup` (object) — optional
  Additional parameters for the `context`.
NOTE: This parameter is required for all contexts except `painless_test`, which is the default if no value is provided for `context`.
  - `document` (object) — required
    Document that's temporarily indexed in-memory and accessible from the script.
  - `index` (string) — required
    Index containing a mapping that's compatible with the indexed document.
You may specify a remote index by prefixing the index with the remote cluster alias.
For example, `remote1:my_index` indicates that you want to run the painless script against the "my_index" index on the "remote1" cluster.
This request will be forwarded to the "remote1" cluster if you have configured a connection to that remote cluster.

NOTE: Wildcards are not accepted in the index expression for this endpoint.
The expression `*:myindex` will return the error "No such remote cluster" and the expression `logs*` or `remote1:logs*` will return the error "index not found".
  - `query` ({} Query) — optional
    Use this parameter to specify a query for computing a score.
    See [Query](https://www.elastic.co/elastic/docs-builder/docs/4641/api/doc/elasticsearch/v9/types/_types-query_dsl-querycontainer)
- `script` (string) — optional
  The Painless script to run.

## Response

`application/json`

- `result` (object)
## Code examples

### Test context

#### Console

```console
POST /_scripts/painless/_execute
{
  "script": {
    "source": "params.count / params.total",
    "params": {
      "count": 100.0,
      "total": 1000.0
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.scriptsPainlessExecute({
  script: {
    source: "params.count / params.total",
    params: {
      count: 100,
      total: 1000,
    },
  },
});
```

#### Python

```python
resp = client.scripts_painless_execute(
    script={
        "source": "params.count / params.total",
        "params": {
            "count": 100,
            "total": 1000
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_scripts/painless/_execute" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "script": {
      "source": "params.count / params.total",
      "params": {
        "count": 100,
        "total": 1000
      }
    }
  }'
```

#### Java

```java
client.scriptsPainlessExecute(s -> s
    .script(sc -> sc
        .source(so -> so
            .scriptString("params.count / params.total")
        )
        .params(Map.of("total", JsonData.fromJson("1000"),"count", JsonData.fromJson("100")))
    )
);
```

#### C#

```c#
var response = await client
    .ScriptsPainlessExecuteAsync<MyDocument, MyDocument>(d1 => d1
        .Script(d2 => d2
            .Params(new Dictionary<string, object>()
            {
                { "count", 100 },
                { "total", 1000 }
            })
            .Source("params.count / params.total")
        )
    );
```

#### PHP

```php
$resp = $client->scriptsPainlessExecute([
    "body" => [
        "script" => [
            "source" => "params.count / params.total",
            "params" => [
                "count" => 100,
                "total" => 1000,
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.scripts_painless_execute(
  body: {
    "script": {
      "source": "params.count / params.total",
      "params": {
        "count": 100,
        "total": 1000
      }
    }
  }
)
```

### Filter context

#### Console

```console
POST /_scripts/painless/_execute
{
  "script": {
    "source": "doc['field'].value.length() <= params.max_length",
    "params": {
      "max_length": 4
    }
  },
  "context": "filter",
  "context_setup": {
    "index": "my-index-000001",
    "document": {
      "field": "four"
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.scriptsPainlessExecute({
  script: {
    source: "doc['field'].value.length() <= params.max_length",
    params: {
      max_length: 4,
    },
  },
  context: "filter",
  context_setup: {
    index: "my-index-000001",
    document: {
      field: "four",
    },
  },
});
```

#### Python

```python
resp = client.scripts_painless_execute(
    script={
        "source": "doc['field'].value.length() <= params.max_length",
        "params": {
            "max_length": 4
        }
    },
    context="filter",
    context_setup={
        "index": "my-index-000001",
        "document": {
            "field": "four"
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_scripts/painless/_execute" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"script":{"source":"doc[' \
  "'" \
  'field' \
  "'" \
  '].value.length() <= params.max_length","params":{"max_length":4}},"context":"filter","context_setup":{"index":"my-index-000001","document":{"field":"four"}}}'
```

#### Java

```java
client.scriptsPainlessExecute(s -> s
    .context(PainlessContext.Filter)
    .contextSetup(c -> c
        .document(JsonData.fromJson("""
{"field":"four"}
"""))
        .index("my-index-000001")
    )
    .script(sc -> sc
        .source(so -> so
            .scriptString("doc['field'].value.length() <= params.max_length")
        )
        .params("max_length", JsonData.fromJson("4"))
    )
);
```

#### C#

```c#
var response = await client
    .ScriptsPainlessExecuteAsync<MyDocument, MyDocument>(d1 => d1
        .Context(PainlessContext.Filter)
        .ContextSetup(d2 => d2
            .Document(JsonSerializer.Deserialize<JsonElement>("""
            {
              "field": "four"
            }
            """))
            .Index("my-index-000001")
        )
        .Script(d2 => d2
            .Params(new Dictionary<string, object>()
            {
                { "max_length", 4 }
            })
            .Source("doc['field'].value.length() <= params.max_length")
        )
    );
```

#### PHP

```php
$resp = $client->scriptsPainlessExecute([
    "body" => [
        "script" => [
            "source" => "doc['field'].value.length() <= params.max_length",
            "params" => [
                "max_length" => 4,
            ],
        ],
        "context" => "filter",
        "context_setup" => [
            "index" => "my-index-000001",
            "document" => [
                "field" => "four",
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.scripts_painless_execute(
  body: {
    "script": {
      "source": "doc['field'].value.length() <= params.max_length",
      "params": {
        "max_length": 4
      }
    },
    "context": "filter",
    "context_setup": {
      "index": "my-index-000001",
      "document": {
        "field": "four"
      }
    }
  }
)
```

### Score context

#### Console

```console
POST /_scripts/painless/_execute
{
  "script": {
    "source": "doc['rank'].value / params.max_rank",
    "params": {
      "max_rank": 5.0
    }
  },
  "context": "score",
  "context_setup": {
    "index": "my-index-000001",
    "document": {
      "rank": 4
    }
  }
}
```

#### JavaScript

```javascript
const response = await client.scriptsPainlessExecute({
  script: {
    source: "doc['rank'].value / params.max_rank",
    params: {
      max_rank: 5,
    },
  },
  context: "score",
  context_setup: {
    index: "my-index-000001",
    document: {
      rank: 4,
    },
  },
});
```

#### Python

```python
resp = client.scripts_painless_execute(
    script={
        "source": "doc['rank'].value / params.max_rank",
        "params": {
            "max_rank": 5
        }
    },
    context="score",
    context_setup={
        "index": "my-index-000001",
        "document": {
            "rank": 4
        }
    },
)
```

#### curl

```curl
curl -X POST "$ELASTICSEARCH_URL/_scripts/painless/_execute" \
  -H "Authorization: ApiKey $ELASTIC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"script":{"source":"doc[' \
  "'" \
  'rank' \
  "'" \
  '].value / params.max_rank","params":{"max_rank":5}},"context":"score","context_setup":{"index":"my-index-000001","document":{"rank":4}}}'
```

#### Java

```java
client.scriptsPainlessExecute(s -> s
    .context(PainlessContext.Score)
    .contextSetup(c -> c
        .document(JsonData.fromJson("""
{"rank":4}
"""))
        .index("my-index-000001")
    )
    .script(sc -> sc
        .source(so -> so
            .scriptString("doc['rank'].value / params.max_rank")
        )
        .params("max_rank", JsonData.fromJson("5"))
    )
);
```

#### C#

```c#
var response = await client
    .ScriptsPainlessExecuteAsync<MyDocument, MyDocument>(d1 => d1
        .Context(PainlessContext.Score)
        .ContextSetup(d2 => d2
            .Document(JsonSerializer.Deserialize<JsonElement>("""
            {
              "rank": 4
            }
            """))
            .Index("my-index-000001")
        )
        .Script(d2 => d2
            .Params(new Dictionary<string, object>()
            {
                { "max_rank", 5 }
            })
            .Source("doc['rank'].value / params.max_rank")
        )
    );
```

#### PHP

```php
$resp = $client->scriptsPainlessExecute([
    "body" => [
        "script" => [
            "source" => "doc['rank'].value / params.max_rank",
            "params" => [
                "max_rank" => 5,
            ],
        ],
        "context" => "score",
        "context_setup" => [
            "index" => "my-index-000001",
            "document" => [
                "rank" => 4,
            ],
        ],
    ],
]);
```

#### Ruby

```ruby
response = client.scripts_painless_execute(
  body: {
    "script": {
      "source": "doc['rank'].value / params.max_rank",
      "params": {
        "max_rank": 5
      }
    },
    "context": "score",
    "context_setup": {
      "index": "my-index-000001",
      "document": {
        "rank": 4
      }
    }
  }
)
```

## Response examples

#### Test context

`application/json`

A successful response from `POST /_scripts/painless/_execute` with a `painless_test` context.

```json
{
  "result": "0.1"
}
```

#### Filter context

`application/json`

A successful response from `POST /_scripts/painless/_execute` with a `filter` context.

```json
{
  "result": true
}
```

#### Score context

`application/json`

A successful response from `POST /_scripts/painless/_execute` with a `score` context.

```json
{
  "result": 0.8
}
```

