Use of a script to aggregate by day of the weekedit

There are some cases where date histogram can’t help us, like for example, when we need to aggregate the results by day of the week. In this case to overcame the problem, we can use a script that returns the day of the week:

POST /sales/_search?size=0
{
    "aggs": {
        "dayOfWeek": {
            "terms": {
                "script": {
                    "lang": "painless",
                    "source": "doc['date'].value.dayOfWeek"
                }
            }
        }
    }
}

Response:

{
  ...
  "aggregations": {
    "dayOfWeek": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "7",
          "doc_count": 4
        },
        {
          "key": "4",
          "doc_count": 3
        }
      ]
    }
  }
}

The response will contain all the buckets having as key the relative day of the week: 1 for Monday, 2 for Tuesday… 7 for Sunday.