title: How to paginate sorted data (with terms aggregation) using composite aggrgation?
body: <p>How to write a pipeline aggregation to paginate the sorted data.[where sorting is done using terms aggregation based on its sub-aggregation]</p>
  <pre><code>GET index_name/_search
  {
      &quot;query&quot;:{&lt;some querying&gt;}
      &quot;aggs&quot;: {
      &quot;pagination&quot;: {
        &quot;composite&quot;: {
          &quot;sources&quot;: [
            {
              &quot;grouping&quot;: {
                &quot;terms&quot;: {
                  &quot;field&quot;: &quot;field_name.keyword&quot;,
                  &quot;order&quot;: &quot;desc&quot;
                }
              }
            }
          ]
        },
        &quot;aggs&quot;: {
          &quot;results&quot;: {
            &quot;terms&quot;: {
              &quot;field&quot;: &quot;field_name.keyword&quot;,
              &quot;order&quot;: {
                &quot;sub_aggregation&quot;: &quot;desc&quot;
              }
            },
            &quot;aggs&quot;: {
              &quot;sub_aggregation&quot;: {
                &quot;filter&quot;: {
                  &quot;term&quot;: {
                    &quot;field_name&quot;: &quot;value&quot;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  
  
  </code></pre>
  <p>The main problem is merging the following 2 sub-problems</p>
  <p>P1. Sorting data based on selected key for which I used terms aggregation and inside the order of the same I have the sub-aggregation.</p>
  <p>P2. I want to paginate the above-sorted data, I have used composite aggregation with terms aggregation.</p>
  <p>When the composite aggregation is sub-aggregation to the terms aggregation. I get the following error:</p>
  <p><code> [composite] aggregation cannot be used with a parent aggregation of type: [TermsAggregatorFactory]</code></p>
  <p>and when I try the vice versa I get paginated data of terms data(P2) separately and sorting(P1) data in separate buckets.</p>
  <p>How can I merge these two problems?</p>