title: parse deeply nested elasticsearch aggregations using it's client API
body: <p>I am using Java client API to get aggregations back. Following is the structure which I am dealing with.</p>
  
  <pre><code>aggregations
  top_models
     buckets
         key : "BMW"
        doc_count : 3
        top_models
             buckets
                 key : "X5"
                 doc_count : 2
                top_hits
                     source
                        model : X5
                        color : Red
                    source
                       model:X5
                      color : White
             key : "X3"
                 doc_count : 1
                top_hits
                     source
                        model : X3
                        color : Red
        key : "Mercedes"
        doc_count : 2
        top_models
             buckets
                 key : "Benz"
                 doc_count : 1
                 top_hits
                     source
                        model : Benz
                        color : Red
  
                key : "ML"
                doc_count : 1
                top_hits
                     source
                        model : ML
                        color : Black
  </code></pre>
  
  <p>I am trying following (toy) code to retrieve all the results. </p>
  
  <pre><code>def getAggregations(aggres: Option[Aggregations]): Option[Iterable[Any]] = {
  
  
  aggres map { agg =&gt;
  
  
    val aggS = agg.asMap().asScala
  
  
    aggS map {
  
  
      case (name, termAgg: Terms) =&gt; getBuckets(Option(termAgg.getBuckets()))
  
  
      case (name, topHits: TopHits) =&gt;
  
  
        val tHits = Option(topHits.getHits())
  
  
        tHits map { th =&gt; getTopHits(th.asScala)
      }
  
  
      case (h, a: InternalAvg) =&gt; println(h + "=&gt;" + a.getValue());
  
  
    }
  
  
  
  
  
  }
  
  
  }
  
  
  
  
  
  def getBuckets(buckets: Option[java.util.Collection[Bucket]]) = {
  
  
  buckets map { bks =&gt;
  
  
    val bksS = bks.asScala
  
  
    bksS map { b =&gt;
  
  
      println("Bucket Key =&gt;" + b.getKey())
  
  
      println("Doc count =&gt;" + b.getDocCount())
  
  
      getAggregations(Option(b.getAggregations())
  
  
    }
  
  
    }
  
   }
  </code></pre>
  
  <p>need to populate final result to this class </p>
  
  <pre><code>case class FinalResponse(bucketName: String, count: Long, children: List[FinalResponse])
  </code></pre>
  
  <p>With nested relationship between Aggregations and Buckets it's becoming convoluted to retrieve all aggregation results. how do you approach this?</p>