Aggregate sum till specific threshold reached

Hi all,

We are storing products in an index. Each product has a price and a specific quantity. Now we want to get the list of cheapest products up till a maximum quantity of 100.

The total quantity should be a sum aggregation. This is something we can do easily. However, how can we run the cheapest products for a specific max quantity (aggregated).

I have been trying to run a scripted metric as follows:

"limited_sum": {
            "scripted_metric": {
                "init_script": "state['my_hash'] = new HashMap();state['my_hash'].put('total_quantity', 0);state['my_hash'].put('total_price', 0.0);state['my_hash'].put('docs', new ArrayList());",
                "map_script": "if(state['my_hash']['total_quantity'] <= 100) {   state['my_hash']['total_quantity'] += doc.available_quantity.value;state['my_hash']['total_price'] += doc.price.value;state['my_hash']['docs'].add(doc.price.value); }",
                "combine_script": "return state['my_hash']",
                "reduce_script": "return states[0]"
            }
        }

This seems to running fine and only gives us back the prices for the products where the quantity is smaller or equal to 100. However the prices are not sorted from the lowest to the highest.

Any help here would be much appreciated!