Question: I would like to aggragate data on documetns which have different days e.g. the hours from 12 to 18 only on THURSDAY.

My query including aggregation looks like this:

```
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "locationid.raw": "HH-44-6"
            }
        },
        {
          "match": {
            "day.keyword": "THURSDAY"
            }
        },
        {
          "range": {
            "dataHour": {
              "from": "12",
              "to": "18",
              "include_lower": true,
              "include_upper": true
            }
          }
        },
        {
          "range": {
            "dataDate": {
              "gte": "2018-11-08 12:00",
              "include_lower": true
            }
          }
        }
      ]
    }
  },
  "aggs" : {
    "contacts" : {
      "date_histogram" : {
        "field" : "dataDate",
        "interval" : "hour"
      },
      "aggs": {
        "seeing_data": {
          "avg": {
            "field": "seeing"
          }
        }
      }
   }
}

```

The response is to big because it gives the aggregates the data in the interval for every day and hour between the startdate of '2018-11-08 18:00' and now, instead of only the three available days (because from 2018-11-08 until now are only three THURSDAYS).

How can i achieve it to only aggregate data within the the hour range of 12-18 and only the THURSDAYS starting at 2018-11-08 12:00?

Answer: 
Get through theses steps to be able to aggregate your data **by hours of a day** :

So you have a date field in your document. You can't from that extract hours. So you have to create a custom field in Kibana.

1. Go to the "Management" section
2. Go to "Index patterns"
3. Go to "Create index pattern"
4. Choose your collection
5. Go to the "Script fields" tab
6. Click on "Add scripted field"

Now we will add the `hour` field :

1. In the "name" field, enter "hour".
2. Set the type to "number".
3. And put in the "script" field : `doc['myDateField'].date.hourOfDay`, where `myDateField` is a field with the date of your document.

There it is ! You can now find your new field in the Discover or Visualize sections.
[![New hour field](https://i.stack.imgur.com/jmRsU.png)](https://i.stack.imgur.com/jmRsU.png)

Here, I aggregate the number of data I've received by hours :
[![Aggregation by hour](https://i.stack.imgur.com/CrXXq.png)](https://i.stack.imgur.com/CrXXq.png)

Find more types of aggregation (for example, `date.dayOfWeek`) here :

<https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-expression.html#_date_field_api>
You could use a script filter

```
"script": {
          "script": "doc['@timestamp'].date.dayOfWeek == 2"
        }

```