Search code examples
sortingelasticsearchelasticsearch-pluginelasticsearch-2.0

Elasticsearch:: Sorting giving weird results


When I am searching the for the first time, its sorting all documents and giving me the first 5 records. However, if same search query is executed by changing the sort direction(ASC -> DESC), then its not sorting all documents again, its giving me last 5 retrieved documents(from previous search query), sorting them in desc order, and giving it back to me. I was expecting that it will sort all available documents in DESC order, and then retrieve first 5 results.

Am I doing something wrong, or missed any concept.

My search query:

{
    "sort": {
        "taskid": {
            "order": "ASC"
        }
    },
    "from": 0,
    "size": 5,
    "query": {
        "filtered": {
            "query": {
                "match_all": []
            }
        }
    }
}

I have data with taskid 1 to 100. Now above query fetched me record from taskid 1 to 5 in first attempt. Now when I changed the sort direction to desc, I was expecting documents with taskid 96-100(100,99,98,97,96 sequence) should be returned, however I was returned documents with taskid 5,4,3,2,1 in that sequence. Which meant, sorting was done on previous returned result only.

Please note that taskid and _id are same in my document. I had added a redundant field in my mapping which will be same as _id


Solution

  • Just change the case of the value in order key and you are good to go.

    {
    "sort": {
        "taskid": {
            "order": "asc"   // or "desc"
        }
    },
    "from": 0,
    "size": 5,
    "query": {
        "filtered": {
            "query": {
                "match_all": []
            }
        }
      }
    }
    

    Hope this helps..