title: ElasticSearch multi level parent-child aggregation
body: <p>I have a parent/child structure in 3 levels. Let's say:<br/></p>
  
  <blockquote>
    <p>Company -> Employee -> Availability</p>
  </blockquote>
  
  <p>Since Availability (and also Employee) is frequently updated here, I choose using parent/child structure against nested. And search function works fine (all documents in correct shards).</p>
  
  <p>Now I want to sort those results. Sorting them by meta data from company (1st level) is easy. But I need to sort also by 3rd level (availability).</p>
  
  <p>I want list of companies which are sorted by:</p>
  
  <ul>
  <li>Distance from location given ASC</li>
  <li>Rating DESC</li>
  <li>Soonest availability ASC</li>
  </ul>
  
  <p>For example:</p>
  
  <p>Company A is 5 miles away, has rating 4 and soonest one of their employees is available in 20 hours
  Company B is also 5 miles away, also has rating 4 but soonest one of their employee is available in 5 hours.</p>
  
  <p>Therefore sort result needs to be B, A.</p>
  
  <p>I would like to append special weight to each of this data, so I started writing aggregations which I could later use in my custom_score script. </p>
  
  <p><strong><a href="https://gist.github.com/PeteMinus/13617fe53973fed79f64" rel="noreferrer">Full gist for creating index, importing data and searching</a></strong>
  <br/> <br/>Now, I've managed to write a query which actually returns back result, but availability aggregation bucket is empty.
  However, I'm also getting results back too structured, I would like to flatten them. </p>
  
  <p>Currently I get back:<br/></p>
  
  <blockquote>
    <p>Company IDS -> Employee IDS -> first availability</p>
  </blockquote>
  
  <p>I would like to have aggregation like:<br/></p>
  
  <blockquote>
    <p><strong>Company IDS -> first availability</strong></p>
  </blockquote>
  
  <p>This way I'm able to do my <code>custom_score</code> script to calculate score and sort them properly.</p>
  
  <p>More simplified question:<br/>
  How can one sort/aggregate by multi level (grand)children and possibly flatten the result.</p>