'Elastic Search query sub arrays

I am trying to query a data shape of:

{
  "took": 26,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 112,
      "relation": "eq"
    },
    "max_score": 6.4646163,
    "hits": [
      {
        "_index": "types",
        "_type": "_doc",
        "_id": "testid1",
        "_score": 6.4646163,
        "_ignored": [
          "polygon"
        ],
        "_source": {
          "app_no": "2014/1234/XXX",
          "actual_completion_date": "27/06/2014",
          "application_details": {
            "details": {
              "units": [
                {
                  "type": "Type 1"
                },
                {
                  "type": "Type 2"
                },
                {
                  "type": "Type 1"
                }
              ]
            }
          },
          "status": "Completed"
        }
      },
      {
        ...
      }
    ]
  }
}

I would like to count all occurrences of the term Type 1, but I'm having a lot of trouble. I think because of the array of units. I'm not even sure how to start searching, is this a sub-query, filter, flattened structure. I know this is really open ended, but any guidance, would be appreciated.



Solution 1:[1]

If you make units array nested, you can achieve this by a nested aggregation.

Example mapping:

{
  "index-name" : {
    "mappings" : {
      "properties" : {
        "application_details" : {
          "properties" : {
            "details" : {
              "properties" : {
                "units" : {
                  "type" : "nested",
                  "properties" : {
                    "type" : {
                      "type" : "keyword"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Example query:

{
  "size": 0, 
  "aggs": {
    "types": {
      "nested": {
        "path": "application_details.details.units"
      },
      "aggs": {
        "types": {
          "terms": {
            "field": "application_details.details.units.type",
            "size": 10
          }
        }
      }
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YD9