# Elasticsearch sort works on and off

**URL:** <https://discuss.elastic.co/t/elasticsearch-sort-works-on-and-off/205188>\
**Category:** Elasticsearch\
**Created:** [October 25, 2019, 6:03am UTC](https://discuss.elastic.co/t/elasticsearch-sort-works-on-and-off/205188 "2019-10-25T06:03:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![May](https://avatars.discourse-cdn.com/v4/letter/m/58f4c7/32.png) [@May](https://discuss.elastic.co/u/May)\
**Post date:** [October 25, 2019, 6:03am UTC](https://discuss.elastic.co/t/elasticsearch-sort-works-on-and-off/205188/1 "2019-10-25T06:03:31Z")

</div>

I am querying index in ES using below code

```auto
def cat_results_tmp(response):
	results=[]
	for hit in response['hits']['hits']:
		result_tuple = (hit["_source"]["fieldA"],hit["_source"]["fieldB"]
						)
		results.append(result_tuple)
	return results       

def cats(cat_sort_field="", sort_order="",country=["US"],cat=[]):
	client = Elasticsearch([{'host':host,'port':9200}])
	response = client.search( \
	index="cat", \
	body={\
		"query": {\
	  "constant_score" : {
	   "filter":{
		"bool":{
		"must":[
		{"terms":{"country.keyword":country}},
		{"bool":{
		"should":[
		{"terms": {"lvl0.keyword":cat[0]}}
		,{"terms": {"lvl1.keyword":cat[1]}},
		{"terms": {"lvl2.keyword":cat[2]}},
		{"terms": {"lvl3.keyword":cat[3]}}
		]
		}}]}}}}
	   ,"sort" : [
		 { cat_sort_field: {"order" : sort_order} }]
		,"size":100
		}
		)
	response3=cat_results_tmp(response)
	return response3

#get sort by fieldA asc result
	print(cats(cat_sort_field="fieldA",sort_order="asc",country=['US'],cat=[[''], [''], ['helloworld']]))
#get sort by fieldB desc result
	print(cats(cat_sort_field="fieldB",sort_order="desc",country=['US'],cat=[[''], [''], ['helloworld']]))

```

While the second one works as expected, the first one does not return sorted result.  
I have tried casting fieldA to double with below, but still can't get sorted result.

```auto
curl -XPUT "http://host/cat/_mappings" -d '
 {
    "properties": {
      "fieldA": { "type": "double" }
    }
  }' -H 'Content-Type: application/json'

```

What is possibly going wrong here? Thanks.

---

<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 22, 2019, 6:03am UTC](https://discuss.elastic.co/t/elasticsearch-sort-works-on-and-off/205188/2 "2019-11-22T06:03:33Z")

</div>

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