Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch - Get aggregation key sort as number

I made query result that aggregate some data, and its aggregation key is number. I tried to sort result of aggregation by key. elasticsearch treated key as string.

Since the number of current result bucket is pretty large, it's unable to modify on client side. Any idea of this?

Here is my query.

"aggregations" : {
                "startcount" : {
                    "terms" : {
                        "script" : "round(doc['startat'].value/1000)",
                        "size" : 1000,
                        "order" : { "_term" : "asc" }
                    }
                }
             }

and current result bucket.

    "buckets": [
       {
          "key": "0",
          "doc_count": 68
       },
       {
          "key": "1",
          "doc_count": 21
       },
       {
          "key": "10",
          "doc_count": 6
       },
       {
          "key": "11",
          "doc_count": 16
       },

It's my expect result.

"buckets": [
   {
      "key": "0",
      "doc_count": 68
   },
   {
      "key": "1",
      "doc_count": 21
   },
   {
      "key": "2", // not '10'
      "doc_count": 6
   },
   {
      "key": "3", // not '11'
      "doc_count": 16
   },
like image 857
J.Done Avatar asked Dec 18 '22 13:12

J.Done


1 Answers

Using the value_script approach should fix the alphabetical sort issue:

Example:

 {
   "size": 0,
   "aggregations": {
      "startcount": {
         "terms": {
            "field": "startat",
            "script": "round(_value/1000)",
            "size": 1000,
            "order": {
               "_term": "asc"
            }
         }
      }
   }
}
like image 157
keety Avatar answered Jan 15 '23 08:01

keety