# Equivalent to sort by "mode and nested filter" in aggs and query

**URL:** <https://discuss.elastic.co/t/equivalent-to-sort-by-mode-and-nested-filter-in-aggs-and-query/35412>\
**Category:** Elasticsearch\
**Created:** [November 24, 2015, 9:38am UTC](https://discuss.elastic.co/t/equivalent-to-sort-by-mode-and-nested-filter-in-aggs-and-query/35412 "2015-11-24T09:38:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sergio](https://avatars.discourse-cdn.com/v4/letter/s/b77776/32.png) [@sergio](https://discuss.elastic.co/u/sergio)\
**Post date:** [November 24, 2015, 9:38am UTC](https://discuss.elastic.co/t/equivalent-to-sort-by-mode-and-nested-filter-in-aggs-and-query/35412/1 "2015-11-24T09:38:00Z")

</div>

Hi,

I have this mapping example:

```
{
   "exampleobject": {
      "properties": {
         "name": {"type":"string"},
         "comments": {
            "type":"nested",            
               "properties": {               
                  "comment": {"type":"string"},
                  "value": {"type":"integer"}
               }
            }
        }
    }
}

```

I can sort my exampleobjects by the sum of its nested field "comments.value", but only the values of the comments who match a query in nested field "comments.comment":

```
'sort': {
    'comments.value': {
        'mode': 'sum',
        'order': 'desc',
        'nested_filter': {
            'query': {'match' :{'comments.comment': 'XXXXXX'}}
        }
    }
}

```

With this sorting, elastic filters the nested object "comments" by the query, then sums their value by exampleobject and finally orders the exampleobjects by its sum.

This works ok, but I need to aggregate and query too in this way and I dont know how to do it. There is an equivalent of the "mode and nested filter" in ES 1.7 in aggregations and queries?

I would like to have a range aggregation (or an histogram) of these nested sums filtered by a query. For example, I would like a response like this:

```
"aggregations": {
    "sumofvalue_filteredby_commentXXXX" : {
        "buckets": [
            { "to": 50, "doc_count": 400},
            { "from": 50, "to": 100, "doc_count": 200},
            { "from": 100, "doc_count": 100}
        ]
    }
}

```

And of course, I need to query my exampleobjects with a range query of these nested and filtered sums. For example, retrieve only the exampleobjects of the bucket from:50 to:100

Do you know how to do it?

Thanks a lot,  
Sergio

---

<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:** [July 5, 2017, 11:36pm UTC](https://discuss.elastic.co/t/equivalent-to-sort-by-mode-and-nested-filter-in-aggs-and-query/35412/2 "2017-07-05T23:36:24Z")

</div>


