# Number of Nested objects

**URL:** <https://discuss.elastic.co/t/number-of-nested-objects/324050>\
**Category:** Elasticsearch\
**Tags:** runtime-fields\
**Created:** [January 26, 2023, 5:18pm UTC](https://discuss.elastic.co/t/number-of-nested-objects/324050 "2023-01-26T17:18:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ewolfman](https://avatars.discourse-cdn.com/v4/letter/e/5f8ce5/32.png) [@ewolfman](https://discuss.elastic.co/u/ewolfman)\
**Post date:** [January 26, 2023, 5:18pm UTC](https://discuss.elastic.co/t/number-of-nested-objects/324050/1 "2023-01-26T17:18:41Z")

</div>

Hi,  
Looking for a way to get the number of nested objects, for querying, sorting etc.  
For example:

```auto
PUT my-index-000001
{
  "mappings": {
    "properties": {
      "some_id": {"type": "long"},
      "user": {
        "type": "nested",
        "properties": {
          "first": {
            "type": "keyword"
          },
          "last": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

PUT my-index-000001/_doc/1
{
  "some_id": 111,
  "user" : [
    {
      "first" : "John",
      "last" : "Smith"
    },
    {
      "first" : "Alice",
      "last" : "White"
    }
  ]
}

```

How to filter by the number of user (e.g. query fetching all documents with more than XX users).

I was thinking to using a runtime\_field but this gives an error:

```auto
GET my-index-000001/_search
{
  "runtime_mappings": {
    "num": {
      "type": "long",
      "script": {
        "source": "emit(doc['some_id'].value)"
      }
    },
    "num1": {
      "type": "long",
      "script": {
        "source": "emit(doc['user'].size())" // <- this breaks with "No field found for [user] in mapping"
      }
    }
  }
  ,"fields": [
    "num","num1"
  ]
}

```

Also tried using aggregations. The following sample gives me the correct doc\_count but is there a way to filter by it?

```auto
GET my-index-000001/_search
{
  "size": 0,
  "aggs": {
    "aaa": {
      "nested": {
        "path": "user"
      }
    }
  }
}

```

Would also be nice to know if I can sort the results (e.g. all documents with more than XX and sorted desc by XX).

Thanks.

---

<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:** [February 23, 2023, 5:18pm UTC](https://discuss.elastic.co/t/number-of-nested-objects/324050/2 "2023-02-23T17:18:46Z")

</div>

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