From 2eafbaf7590bcb8219dcb55ecc28db6ade9a92e8 Mon Sep 17 00:00:00 2001 From: matarrese Date: Fri, 7 Jul 2017 19:16:53 +0100 Subject: [PATCH] Document aggregating by day of the week (#25602) Add documentation for aggregating by day of the week. Closes #24660 --- .../bucket/datehistogram-aggregation.asciidoc | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc b/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc index 47265a0b224..3029b28df3b 100644 --- a/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc +++ b/docs/reference/aggregations/bucket/datehistogram-aggregation.asciidoc @@ -397,3 +397,58 @@ By default the returned buckets are sorted by their `key` ascending, though the the `order` setting. Supports the same `order` functionality as the <>. deprecated[6.0.0, Use `_key` instead of `_time` to order buckets by their dates/keys] + +=== Use of a script to aggregate by day of the week + +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: + + +[source,js] +-------------------------------------------------- +POST /sales/_search?size=0 +{ + "aggs": { + "dayOfWeek": { + "terms": { + "script": { + "lang": "painless", + "source": "doc['date'].value.dayOfWeek" + } + } + } + } +} +-------------------------------------------------- +// CONSOLE +// TEST[setup:sales] + +Response: + +[source,js] +-------------------------------------------------- +{ + ... + "aggregations": { + "dayOfWeek": { + "doc_count_error_upper_bound": 0, + "sum_other_doc_count": 0, + "buckets": [ + { + "key": "7", + "doc_count": 4 + }, + { + "key": "4", + "doc_count": 3 + } + ] + } + } +} +-------------------------------------------------- +// TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/] + +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. \ No newline at end of file