Jay Prakash Meena
Jay Prakash Meena

Reputation: 11

Hourly aggregation from timestamp field in Elasticsearch and Java API

Is it possible to retrieve hourly buckets from timestamp field using terms aggregation and inline script using elasticsearch Rest HL client.

https://discuss.elastic.co/t/hourly-aggregation-for-timestamp-and-java-api-irrespective-of-date/109575

How can we achieve the below query using Elasticsearch Java HL Rest client ?

# script in terms aggs.
GET /pixeluidevent/uidevent/_search
{
"size": 0, 
"query": {
"bool": {
    "must": [ { "match": { "name": "testName"  }}]
    }
  },
  "aggs": {
    "BY_DAYOFWEEK": {
      "terms": {
        "script": {
          "lang": "painless",
          "inline": "doc['eventTime'].date.hourOfDay"
        }
       }
    }
   }
}

Part of Response

"buckets": [
    {
      "key": "6",
      "doc_count": 36821
    },
    {
      "key": "0",
      "doc_count": 34000
    },
    {
      "key": "3",
      "doc_count": 30153
    },
    {
      "key": "2",
      "doc_count": 29452
    }
  ]

Thanks

Upvotes: 1

Views: 459

Answers (1)

Jay Prakash Meena
Jay Prakash Meena

Reputation: 11

Implemented it using stored Script.

// Code 
Script _script = new Script(ScriptType.STORED, "painless", "doc['eventTime'].date.dayOfWeek", new HashMap<>());

TermsAggregationBuilder termsAggBuilderForDOW = AggregationBuilders.terms("by_day_of_week").script(_script);
termsAggBuilderForDOW.size(7); // 7 size

PFA link for details on this. https://discuss.elastic.co/t/hourly-aggregation-for-timestamp-and-java-api-irrespective-of-date/109575/8

Upvotes: 0

Related Questions