Home > Blockchain >  Append a leading '0' to a string character if it is less than 9, without scripting while q
Append a leading '0' to a string character if it is less than 9, without scripting while q

Time:11-05

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?

CodePudding user response:

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.

  • Related