# Sort by count of nested objects matching two or more criterias

**URL:** https://discuss.elastic.co/t/sort-by-count-of-nested-objects-matching-two-or-more-criterias/45594
**Category:** Elasticsearch
**Created:** [March 28, 2016, 2:33pm UTC](https://discuss.elastic.co/t/sort-by-count-of-nested-objects-matching-two-or-more-criterias/45594 "2016-03-28T14:33:26Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Hendrik\_Dev](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hendrik_dev/32/978_2.png) [@Hendrik\_Dev](https://discuss.elastic.co/u/Hendrik_Dev)
#### Post date: [March 28, 2016, 2:33pm UTC](https://discuss.elastic.co/t/sort-by-count-of-nested-objects-matching-two-or-more-criterias/45594/1 "2016-03-28T14:33:26Z")

</div>

I need to sort by the count of nested objects matching two or more criterias.  
`ncomments` is declared as `type=nested` in the mapping.

The query below throws this exception:

```
"reason" : "failed to run inline script [doc['ncomments'].value] using lang [groovy]",
 "type" : "illegal_argument_exception",
 "reason" : "No field found for [ncomments] in mapping with types []"
```

If there is a solution without scripting (or at least without grovvy scripting) i would prefer that.  
I am using Elasticsearch 2.2

What i tried so far:

```
{
    "query":{
          "match_all":{}
    },
    "sort":[
        {
            "_script":{
                "script":{
                    "inline":"doc['ncomments'].values.length"
                },
                "type":"number",
                "order":"asc",
                "nested_path":"ncomments",
                "nested_filter":{
                    "bool":{
                        "must":[
                            {
                                "term":{
                                    "ncomments.c_status":"public"
                                }
                            },
                            {
                                "range":{
                                    "ncomments.date":{
                                        "lt":"2014-02-01",
                                        "format":"yyyy-MM-dd"
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    ]
}
```

---

<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:04pm UTC](https://discuss.elastic.co/t/sort-by-count-of-nested-objects-matching-two-or-more-criterias/45594/2 "2017-07-05T23:04:40Z")

</div>


