# Is it possible to limit retrieved documents based on a sum aggregation?

**URL:** <https://discuss.elastic.co/t/is-it-possible-to-limit-retrieved-documents-based-on-a-sum-aggregation/249582>\
**Category:** Elasticsearch\
**Created:** [September 22, 2020, 8:33pm UTC](https://discuss.elastic.co/t/is-it-possible-to-limit-retrieved-documents-based-on-a-sum-aggregation/249582 "2020-09-22T20:33:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jmwilkinson](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jmwilkinson/32/65961_2.png) [@jmwilkinson](https://discuss.elastic.co/u/jmwilkinson)\
**Post date:** [September 22, 2020, 8:33pm UTC](https://discuss.elastic.co/t/is-it-possible-to-limit-retrieved-documents-based-on-a-sum-aggregation/249582/1 "2020-09-22T20:33:55Z")

</div>

Lets say i have the documents:

```auto
{"name": "foo", "size": 1}
{"name": "bar", "size": 10}
{"name": "baz", "size": 2}
{"name": "fred", "size": 5}

```

I could perform the following aggregation:

```auto
POST /my-docs/_search?size=0
{
  "aggs": {
    "total": { 
      "sum": { 
        "field": "size"
      } 
    }
  }
}

```

Which is all well and good.  
But what if I want to retrieve documents until the aggregate "total" value is \>= 13? In that case, I would only want to get the first 3 documents. Is there some way to accomplish this?

---

<div class="post-metadata">

**Author:** ![jmwilkinson](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jmwilkinson/32/65961_2.png) [@jmwilkinson](https://discuss.elastic.co/u/jmwilkinson)\
**Post date:** [September 22, 2020, 11:18pm UTC](https://discuss.elastic.co/t/is-it-possible-to-limit-retrieved-documents-based-on-a-sum-aggregation/249582/2 "2020-09-22T23:18:49Z")

</div>

As a corollary to this, it is possible to only retrieve the first document associated with the aggregation sum crossing a particular threshold, such as every 100 or something?

This likely implies an amount of internal ordering that isn't available, but it's worth a shot....

---

<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:** [October 20, 2020, 11:18pm UTC](https://discuss.elastic.co/t/is-it-possible-to-limit-retrieved-documents-based-on-a-sum-aggregation/249582/3 "2020-10-20T23:18:51Z")

</div>

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