title: Terms aggregation on an inner object and retrieving bucket metadata
body: <p>We index the following products:</p>
  
  <pre><code>{
      "id": "1",
      "name": "the-name",
      "categories": [
          {
              "id" : 10,
              "name" : "cat-1"
          },
          {
              "id" : 20,
              "name" : "cat-2"
          }
      ]
  }
  </code></pre>
  
  <p>We are doing an aggregation on <code>categories.id</code> using : </p>
  
  <pre><code>REQUEST:
  //...
  "aggs": {
      "by_cat": {
          "terms": {
              "field": "categories.id",
              "size": 10
          }
      }
  }
  
  ---
  RESPONSE:
  // ...
  "by_cat" : {
      "buckets" : [
      {
          "key" : 10,
          "doc_count" : 804
      },
      {
          "key" : 20,
          "doc_count" : 327
      },
  </code></pre>
  
  <p>It works well, however, each bucket contains only the <code>categories.id</code> in the <code>key</code> field. What we would like is to be able to have the name of the category in the bucket, for example : </p>
  
  <pre><code>// ...
        "buckets" : [
          {
            "key" : 10,
            "metadata": {
                "name": "cat-1"
            },
            "doc_count" : 804
          },
          {
            "key" : 20,
            "metadata": {
                "name": "cat-2"
            },
            "doc_count" : 327
          },
  </code></pre>
  
  <p>What is the good way to do that ? We found two to get this information but they both looks "hackish" : </p>
  
  <ul>
  <li>Using top_hits with size 1 and source limited to categories, it will retrieve one document per bucket containing the information we need. This first solution doesn't look performance-wise and the more aggregation we have, the more bloated is the response.</li>
  <li>Adding a new column id_name which concatenate id and name and doing the term aggregation on it. It looks more like a hack, and may be complicated if many fields.</li>
  </ul>
  
  <p>We also tried by mixing field and script in terms but it doesn't help. </p>
  
  <p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/agg-metadata.html" rel="nofollow noreferrer">metadata</a> looked exactly what we wanted but it is global for all the buckets and not dynamic.</p>
  
  <p>Do we have other way to retrieve this information ?</p>