elasticsearchelasticsearch-painlesselasticsearch-7scriptedfield

Append a leading '0' to a string character if it is less than 9, without scripting while querying in elasticsearch


I have the problem of strings not being sorted numerically. For eg. 10< 8 instead of 8 <10 I currently cannot convert strings to integers because of other parts of string being literal strings.

I would like to append a leading 0 , if the number is less than 10. How can I achieve that without using scripting?


Solution

  • I will suggest to use below query with sort which have script. This will work best compare to appending leading 0 to value.

    You can replace ID.keyword with your field name.

    {
      "query": {
        "match_all": {}
      },
      "sort": {
        "_script": {
          "type": "Number",
          "order": "desc",
          "script": {
            "lang": "painless",
            "source": "Long.parseLong(doc['ID.keyword'].value)"
          }
        }
      }
    }
    

    If you have integer value then you can used Integer.parseInt(doc['ID.keyword'].value) as well.