Search code examples
ruby-on-railsrubyelasticsearchsearchkick

Average of group by date records in Elasticsearch


I need an average count of records group by date, I am using Elasticsearch and searchkick with Ruby on rails.

For getting records group by date Following code is working:

group_by_date: {
     date_histogram: {
     field: :created_at,
     interval: 'day'
   }
},

I am getting the following output of this code

"group_by_date"=>
  {"buckets"=>
    [{"key_as_string"=>"2020-01-07T00:00:00.000Z",
      "key"=>1578355200000,
      "doc_count"=>14},
      {"key_as_string"=>"2020-01-08T00:00:00.000Z",
      "key"=>1578441600000,
      "doc_count"=>3}
      ]
    }

I want an average of these records here in this case there are two dates So the average should be (14 + 3)/2 = 8.5

Thanks


Solution

  • I got the average by following

            average_properties_by_date:{
              avg_bucket: {
                buckets_path: 'group_by_date>_count',
                gap_policy: "skip",
                format: "#,##0.00;(#,##0.00)"
              }
            }
    

    Be careful here _count will be used instead of doc_count.