1

I'm trying to get number of a string. I'm doing this using a regex pattern. When I get the result, i get something like "1", "10", "2". I want to sort it, so I need to add zero to the left in order to sort them naturally.

My script is here:

{
   "from": 0,
   "size": 40,
   "sort": [
      {
         "fields.myfield.keyword": { "order": "asc" }, 
         "_script": {
            "type": "string",
            "script": {
               "inline": 
               "def m = /(\\d+$)/.matcher(doc['fields.myfield.keyword'].value); 
               if ( m.find() ) 
                { 
                    String s = m.group(1); 
                    String.format(\"%05d\", s.toString()); 
                } 
                else { return 0 }"               
            },
            "order" : "asc"

         }
      }
   ],
   "_source": { "include": ["fields.myfield"] }}

When I try execute the command, I getting the following error:

"failed_shards": [
{
   "shard": 0,
   "index": "myindex",
   "node": "kctN6d5ITrqtIMj4cbChKQ",
   "reason": {
      "type": "script_exception",
      "reason": "compile error",
      "script_stack": [
         "... ; String.format(\"%05d\", s.toString()); } else { re ...",
         "                             ^---- HERE"
      ],
      "script": "def m = /(\\d+$)/.matcher(doc['fields.myfield.keyword'].value); if ( m.find() ) { String s = m.group(1); String.format(\"%05d\", s.toString()); } else { return 0 }",
      "lang": "painless",
      "caused_by": {
         "type": "class_cast_exception",
         "reason": "Cannot cast from [String] to [def[]]."
      }
   }
}

How can I add zeros left without using String.Formatter?

Where am I try to cast from a STRING to DEF?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
NatsuDragonEye
  • 109
  • 5
  • 18

1 Answers1

1

adding zeros requires the type to be number and not a string. have you tried Integer.valueOf(s) instead (just on top of my head, havent verified).

alr
  • 1,744
  • 1
  • 10
  • 11
  • I dont have sure, but left zeros as a integer, I think that will be ignored. I need something like "0001", "0011", in order to sort it naturally. – NatsuDragonEye Aug 02 '17 at 14:59