Suppose I have an index filled with Person
records, and I want to get the doc counts for the top 5 name
s (based on today) over the past week. To clarify, I don't want the top 5 names each day, instead I want to show the counts of today's top 5 names over the past week. Currently, this is my strategy:
{
"aggs": {
"sales_over_time": {
"date_histogram": {
"field": "date",
"calendar_interval": "day",
"extended_bounds": {
"min": "now-7d/d",
"max": "now"
}
},
"aggs": {
"names": {
"terms": {
"field": "name",
"size": 10000
}
}
}
}
}
}
I use a large (10k) size, and filter results based on which names are in the top 5 in today's histogram bucket. However, this is very slow and doesn't guarantee I get all results.
A better way would be to filter the data to only records that have one of the top 5 names of the current day.
I know this could be done by using two queries by having the first fetch the top 5 names of today and using the results to filter the second query that fetches counts over the last 7 days. However, it would be much better for me to do this in one query.
Is there any way this could be done in a single query?