DSL: Substracting Two Fields and List Top 10 with Highest Value

Anyone knows if DSL query can get do something like
field "retail_price" - "cost_price" to get a field "profit" and return a list of top 10 products with most profits.

If your documents have a format similar to this:

{
    "cost_price": 10
    "retail_price": 12
    "product_name": "t-shirt"
}

The you can find the profit for each product using a script and then sum these profits using a sum aggregation. You can then have a terms aggregation for the product_namewhich is ordered by the sum aggregation. So it would be something like the following (not tested):

{
	"aggs": {
		"top_products": {
			"terms": {
				"field": "product_name"
				"size": 10,
				"order": {
				    "profit": "desc"
				}
			},
			"aggs": {
				"profit": {
					"sum": {
						"script": "doc['retail_price'].value - doc['cost_price'].value"
					}
				}
			}
		}
	}
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.