# Aggregation with script code with previous result

**URL:** <https://discuss.elastic.co/t/aggregation-with-script-code-with-previous-result/352836>\
**Category:** Elasticsearch\
**Created:** [February 8, 2024, 9:11am UTC](https://discuss.elastic.co/t/aggregation-with-script-code-with-previous-result/352836 "2024-02-08T09:11:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fnizou](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/fnizou/32/3795_2.png) [@Fnizou](https://discuss.elastic.co/u/Fnizou)\
**Post date:** [February 8, 2024, 9:11am UTC](https://discuss.elastic.co/t/aggregation-with-script-code-with-previous-result/352836/1 "2024-02-08T09:11:51Z")

</div>

Hello everyone

I would like to know if it is possible in 1 single request,

in the aggregations, to make a script which calculates an aggs based on the previous results:

I need to dynamically calculate the interval  
the goal being to find an interval with this formula:

My custom code

```auto
$coef_test = $price_max / $price_min;

if( $coef_test == 0 ){ 
    $step = 2;
}elseif($coef_test > 0 && $coef_test <= 15){    
	$step = 10;
}else{
    $step = 20;
}

$interval = ($price_max - $price_min) / $step;

```

and here is the ES query

{

```
    "size": 0,
    "aggs": {
      "price_min": {
            "nested": {
                "path": "onsale_price.EUR"
            },
            "aggs": {
                "facet_name": {
                    "min": {
                        "field": "onsale_price.EUR.value"
                    }
                }
            }
        },
        "price_max": {
            "nested": {
                "path": "onsale_price.EUR"
            },
            "aggs": {
                "facet_name": {
                    "max": {
                        "field": "onsale_price.EUR.value"
                    }
                }
            }
        },
        
        "price_histogram": {
            "nested": {
                "path": "onsale_price.EUR"
            },
            "aggs": {
                "facet_name": {
                    "histogram": {
                        "field": "onsale_price.EUR.value",
                        "interval": $interval <--------------------------- here
                    }
                }
            }
        }
    }
}

```

Thank you for your light

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [March 7, 2024, 9:12am UTC](https://discuss.elastic.co/t/aggregation-with-script-code-with-previous-result/352836/2 "2024-03-07T09:12:49Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
