﻿---
title: Bucket script aggregation context
description: Use a Painless script in an bucket_script pipeline aggregation to calculate a value as a result in a bucket. The standard Painless API is available. To...
url: https://www.elastic.co/elastic/docs-builder/docs/2889/reference/scripting-languages/painless/painless-bucket-script-agg-context
products:
  - Elasticsearch
  - Painless
applies_to:
  - Elastic Cloud Serverless: Generally available
  - Elastic Stack: Generally available
---

# Bucket script aggregation context
Use a Painless script in an [`bucket_script` pipeline aggregation](https://www.elastic.co/elastic/docs-builder/docs/2889/reference/aggregations/search-aggregations-pipeline-bucket-script-aggregation) to calculate a value as a result in a bucket.

## Variables

<definitions>
  <definition term="params (Map, read-only)">
    User-defined parameters passed in as part of the query. The parameters include values defined as part of the `buckets_path`.
  </definition>
</definitions>


## Return

<definitions>
  <definition term="numeric">
    The calculated value as the result.
  </definition>
</definitions>


## API

The standard [Painless API](https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-api-reference-shared.html) is available.

## Example

To run the example, first [install the eCommerce sample data](/elastic/docs-builder/docs/2889/reference/scripting-languages/painless/painless-context-examples#painless-sample-data-install).
The following request is useful for identifying high-value markets by comparing average order values across countries. It groups orders by country and calculates metrics for each country, including `total_revenue` and `order_count`, then uses a bucket script to compute `revenue_per_order` for performance analysis.
```json
GET kibana_sample_data_ecommerce/_search
{
  "size": 0,
  "aggs": {
    "countries": {
      "terms": {
        "field": "geoip.country_iso_code"
      },
      "aggs": {
        "total_revenue": {
          "sum": {
            "field": "taxful_total_price"
          }
        },
        "order_count": {
          "value_count": {
            "field": "order_id"
          }
        },
        "revenue_per_order": {
          "bucket_script": {
            "buckets_path": {
              "revenue": "total_revenue",
              "orders": "order_count"
            },
            "script": {
              "source": "params.revenue / params.orders"
            }
          }
        }
      }
    }
  }
}
```