# Elastica not grouping aggregation before setScript

**URL:** <https://discuss.elastic.co/t/elastica-not-grouping-aggregation-before-setscript/143128>\
**Category:** Elasticsearch\
**Created:** [August 6, 2018, 9:08am UTC](https://discuss.elastic.co/t/elastica-not-grouping-aggregation-before-setscript/143128 "2018-08-06T09:08:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Islam\_Elshobokshy](https://avatars.discourse-cdn.com/v4/letter/i/77aa72/32.png) [@Islam\_Elshobokshy](https://discuss.elastic.co/u/Islam_Elshobokshy)\
**Post date:** [August 6, 2018, 9:08am UTC](https://discuss.elastic.co/t/elastica-not-grouping-aggregation-before-setscript/143128/1 "2018-08-06T09:08:28Z")

</div>

I have a type product in elasticsearch that contains a column containing multiple ids, some of them are the same.  
There are also columns containing current price and the quantity. I want the to get the sum of price \* avg of each unique id.

```
id price qte
_______  _________
            
1 25 4
1 25 4
1 25 4
2 38 2
2 38 2
3 12 3
3 12 3
3 12 3
3 12 3
4 33 6
5 64 8
5 64 8

```

(if you're wondering why it's like that, it's cuz there are other columns with different values for each)

So I created my aggregation :

```
$id = new \Elastica\Aggregation\Terms('id');
$id->setField('id')->setSize(0);

$qte_price = new \Elastica\Aggregation\Sum('qte_price');
$qte_price->setScript('doc["price"].value * doc["qte"].value');

$id->addAggregation($qte_price);

```

The problem here, is that `qte_price` doesn't use the first aggregation on the `id` before performing the `setScript()`, thus summing the total of `price * qte` on all ids even the repeated ones. What am I doing wrong?

---

<div class="post-metadata">

**Author:** ![Islam\_Elshobokshy](https://avatars.discourse-cdn.com/v4/letter/i/77aa72/32.png) [@Islam\_Elshobokshy](https://discuss.elastic.co/u/Islam_Elshobokshy)\
**Post date:** [August 7, 2018, 8:57am UTC](https://discuss.elastic.co/t/elastica-not-grouping-aggregation-before-setscript/143128/2 "2018-08-07T08:57:42Z")

</div>

Allow me to bump this post 🙂

---

<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:** [September 4, 2018, 8:57am UTC](https://discuss.elastic.co/t/elastica-not-grouping-aggregation-before-setscript/143128/3 "2018-09-04T08:57:43Z")

</div>

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