# Sort by price and stock

**URL:** <https://discuss.elastic.co/t/sort-by-price-and-stock/102719>\
**Category:** Elasticsearch\
**Created:** [October 4, 2017, 3:02pm UTC](https://discuss.elastic.co/t/sort-by-price-and-stock/102719 "2017-10-04T15:02:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![juelisjr](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/juelisjr/32/20241_2.png) [@juelisjr](https://discuss.elastic.co/u/juelisjr)\
**Post date:** [October 4, 2017, 3:02pm UTC](https://discuss.elastic.co/t/sort-by-price-and-stock/102719/1 "2017-10-04T15:02:49Z")

</div>

Hi.

I have a catalog of products and i'm need to sort the result by price and stock. The products with stock equal 0 need to be in end of result but need to be ordered by price.  
Example:

NAME -\> PRICE -\> STOCK  
Product1 -\> 150,00 -\> 10  
Product2 -\> 140,00 -\> 12  
Product3 -\> 135,00 -\> 10  
Product4 -\> 160,00 -\> 0  
Product5 -\> 150,00 -\> 0  
Product6 -\> 140,00 -\> 0

The query i'm using is this:

```
   {
	"from": 0,
	"size": "12",
	"query": {
		"boosting": {
			"positive": {
				"filtered": {
					"query": {
						"bool": {
							"must": [{
								"bool": {
									"should": [{"all queries here"}]
								}
							}]
						}
					},
					"filter": {
						"bool": {
							"some": "filters"
						}
					}
				}
			},
			"negative": {
				"match": {
					"stock_total": 0
				}
			},
			"negative_boost": 0
		}
	},
	"aggs": {
		"some": "aggregations"
	},
	"sort": [
		{"price_facet": {"order": "desc" } }, 
		{"stock_total": {"order": "desc"} },
        {"_score": {"order": "desc"} } 
    ],
	"track_scores": true
}
```

---

<div class="post-metadata">

**Author:** ![Ivan](https://avatars.discourse-cdn.com/v4/letter/i/df788c/32.png) [@Ivan](https://discuss.elastic.co/u/Ivan)\
**Post date:** [October 7, 2017, 10:35pm UTC](https://discuss.elastic.co/t/sort-by-price-and-stock/102719/2 "2017-10-07T22:35:13Z")

</div>

You can first sort on a script field if the stock price is equal to zero.  
You can also create such a field ahead of time, so that you can have better  
performance at the cost of index room.

---

<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:** [November 4, 2017, 10:35pm UTC](https://discuss.elastic.co/t/sort-by-price-and-stock/102719/3 "2017-11-04T22:35:47Z")

</div>

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