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

**URL:** <https://discuss.elastic.co/t/dsl-substracting-two-fields-and-list-top-10-with-highest-value/96741>\
**Category:** Elasticsearch\
**Created:** [August 11, 2017, 9:36am UTC](https://discuss.elastic.co/t/dsl-substracting-two-fields-and-list-top-10-with-highest-value/96741 "2017-08-11T09:36:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gringo](https://avatars.discourse-cdn.com/v4/letter/g/f19dbf/32.png) [@gringo](https://discuss.elastic.co/u/gringo)\
**Post date:** [August 11, 2017, 9:36am UTC](https://discuss.elastic.co/t/dsl-substracting-two-fields-and-list-top-10-with-highest-value/96741/1 "2017-08-11T09:36:38Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![colings86](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/colings86/32/44960_2.png) [@colings86](https://discuss.elastic.co/u/colings86)\
**Post date:** [August 11, 2017, 9:53am UTC](https://discuss.elastic.co/t/dsl-substracting-two-fields-and-list-top-10-with-highest-value/96741/2 "2017-08-11T09:53:58Z")

</div>

If your documents have a format similar to this:

```auto
{
    "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_name`which is ordered by the sum aggregation. So it would be something like the following (not tested):

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

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [September 8, 2017, 9:54am UTC](https://discuss.elastic.co/t/dsl-substracting-two-fields-and-list-top-10-with-highest-value/96741/3 "2017-09-08T09:54:09Z")

</div>

Closed on September 8, 2017, 9:54am UTC

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