I have an elasticsearch aggregation query like this.
{
    "aggs": {
        "customer": {
            "aggs": {
                "Total_Sale": {
                    "sum": {
                        "field": "amount"
                    }
                }
            },
            "terms": {
                "field": "org",
                "size": 50000
            }
        }
    }
}
And it results in bucket aggregation like following
{
    "aggregations": {
        "customer": {
            "buckets": [
                {
                    "Total_Sale": { "value": 9999 },
                    "doc_count": 8,
                    "key": "cats"
                },
                {
                    "Total_Sale": { "value": 8888 },
                    "doc_count": 6,
                    "key": "tigers"
                },
                {
                    "Total_Sale": { "value": 444},
                    "doc_count": 5,
                    "key": "lions"
                },
                {
                    "Total_Sale": { "value": 555 },
                    "doc_count": 2,
                    "key": "wolves"
                }
           ]
       }
    }
}
I want another range bucket aggregation based on doc_count. So, final result required is
{
    "buckets": [    
        {               
            "Sum_of_Total_Sale": 555, // If I can form bucket, I can get this using sum_bucket. So, getting bucket is important.
            "Sum_of_doc_count": 2, 
            "doc_count": 1, 
            "key": "*-3",   
            "to": 3.0       
        },              
        {               
            "Sum_of_Total_Sale": 9332,
            "Sum_of_doc_count": 11,
            "doc_count": 2, 
            "from": 4.0,    
            "key": "4-6",   
            "to": 6.0       
        },                  
        {               
            "Sum_of_Total_Sale": 9999,
            "Sum_of_doc_count": 8,
            "doc_count": 1, 
            "from": 7.0,    
            "key": "7-*"    
        }                   
    ]                   
}  
- Bucket Selector Aggregation and then using bucket sum aggregation will not work because there is more than one key for range.
- Bucket Script Aggregation does calculation within bucket.
- Can I add scripted doc field for each document which help me to create these buckets?
 
    