Mehmet Yener YILMAZ
Mehmet Yener YILMAZ

Reputation: 25

elasticsearch hourly histogram calculation

This dsl returns all the hours in date field of index.. But I need total value of an "hour value" in index. So I just hope 24 buckets as a result each buckets contains a hour and value in this buckets must be total sum of fields("respsize") of all docs that in this hour

{
   "size":0,
   "query":{
      "filtered":{
         "filter":{
         }
      }
   },
   "aggs":{
      "aggs1":{
         "date_histogram":{
            "field":"loggingdate",
            "interval":"hour",
            "format":"k",
            "order":{
               "aggs2":"desc"
            }
         },
         "aggs":{
            "aggs2":{
               "sum":{
                  "field":"respsize"
               }
            }
         }
      }
   }
}

exmp: this returns

"aggs1": {
         "buckets": [
            {
               "key_as_string": "5",
               "key": 1452852000000,
               "doc_count": 29500,
               "aggs2": {
                  "value": 1
               }
            },
            {
               "key_as_string": "6",
               "key": 1452866400000,
               "doc_count": 15941,
               "aggs2": {
                  "value": 2
               }
            },
            {
               "key_as_string": "5",
               "key": 1452870000000,
               "doc_count": 6121,
               "aggs2": {
                  "value": 3
               }
            },

but I want this:

"aggs1": {
         "buckets": [
            {
               "key_as_string": "5",
               "key": 1452852000000,
               "doc_count": 29500,
               "aggs2": {
                  "value": 4
               }
            },
            {
               "key_as_string": "6",
               "key": 1452866400000,
               "doc_count": 15941,
               "aggs2": {
                  "value": 2
               }
            }
            },

Upvotes: 0

Views: 284

Answers (1)

Richa
Richa

Reputation: 7649

You can use terms aggregation then. Use below query:

{
"size":0,
"query":{
  "filtered":{
     "filter":{
     }
  }
},
"aggs":{
  "aggs1":{
     "terms":{
        "script": "new    
DateTime(doc['loggingdate'].value).getHourOfDay()",

        "order":{
           "aggs2":"desc"
        }
     },
     "aggs":{
        "aggs2":{
           "sum":{
              "field":"respsize"
           }
        }
     }
  }
 }
}

I guess it will fetch you the desired result.

Upvotes: 2

Related Questions