Search code examples
elasticsearch

elasticsearch sort by document id


I have a simple index in elasticsearch and all my ids are manually added, i.e. I do not add documents with automatic string ids.

Now the requirement is to get list of all documents page by page and sorted by the document id (i.e. _id)

When I tried this with _id, it did not work. Then I looked for it on forums and found out this much that I have to use _uid for that. This actually works, although I have no clue how. But another problem is that the sorting is done as if the the _id is string. And it actually is a string. But I want the results as if the _id was a number.

So there are two issues here:

  1. Why sorting does not work with _id and it does work with _uid

  2. Is there a way to get document ids sorted as numbers and not integers

For e.g. if my doc ids are 1, 2, 3, ..... , 55

I am getting results in this order:

1, 10, 11, 12, ... , 19, 2, 20, ... so on

While I would like to get the results in this order:

1, 2, 3, ... so on

Any help is highly appreciated!


Solution

  • Have the _id indexed:

    {
      "mappings": {
        "some_type": {
          "_id": {
            "index": "not_analyzed"
          }
        }
      }
    }
    

    And use a script:

    {
      "sort": {
        "_script": {
          "type": "number",
          "script": "doc['_id'].value?.isInteger()?doc['_id'].value.toFloat():null",
          "order": "asc"
        }
      }
    }
    

    Even though I strongly recommend, if possible, changing the id to integer rather having it as string and contain numbers, instead.

    And I kind of doubt that it worked with _uid because _uid is a combination between type and id.