Hi dadoonet, thank you for asking!
First thing: I forgot to mention that we are using ElasticSearch 2.4.5 (I know, such an old version).
My attempts so far (In this simple case I want to take only 3 first ordered hits and aggregate those so the max-number agg return 3 instead of 5 (the maximum of all documents)
(1) Original query:
GET /megacorp/_search
{
"query": {
"filtered": {
"filter": {
"range" : {
"number": {
"gte": 0
}
}
},
"query": {
"match_all": {}
}
}
},
"aggs": {
"max-number": {"max": {"field": "number"}}
},
"sort": [
{ "number" : {"order" : "asc"}}
]
}
(2) Original query - result
{
"took": 8,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 5,
"max_score": null,
"hits": [
{
"_index": "megacorp",
"_type": "employees",
"_id": "1",
"_score": null,
"_source": {
"text": "text1",
"number": 1
},
"sort": [
1
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "2",
"_score": null,
"_source": {
"text": "text1",
"number": 2
},
"sort": [
2
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "3",
"_score": null,
"_source": {
"text": "text2",
"number": 3
},
"sort": [
3
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "4",
"_score": null,
"_source": {
"text": "text2",
"number": 4
},
"sort": [
4
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "5",
"_score": null,
"_source": {
"text": "text2",
"number": 5
},
"sort": [
5
]
}
]
},
"aggregations": {
"max-number": {
"value": 5
}
}
}
(2) Limit filter in aggregation (if I change the limit filter with another condition - ie. number < 3 - I get max = 5, but I need to limit results by number of hits)
GET /megacorp/_search
{
"query": {
"filtered": {
"filter": {
"range" : {
"number": {
"gte": 0
}
}
},
"query": {
"match_all": {}
}
}
},
"aggs": {
"foo": {
"filter": {"limit" : {"value" : 2}},
"aggs": {
"max-number": {"max": {"field": "number"}}
}
}
},
"sort": [
{ "number" : {"order" : "asc"}}
]
}
(2) Limit filter in aggregation - result:
{
"took": 13,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 5,
"max_score": null,
"hits": [
{
"_index": "megacorp",
"_type": "employees",
"_id": "1",
"_score": null,
"_source": {
"text": "text1",
"number": 1
},
"sort": [
1
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "2",
"_score": null,
"_source": {
"text": "text1",
"number": 2
},
"sort": [
2
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "3",
"_score": null,
"_source": {
"text": "text2",
"number": 3
},
"sort": [
3
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "4",
"_score": null,
"_source": {
"text": "text2",
"number": 4
},
"sort": [
4
]
},
{
"_index": "megacorp",
"_type": "employees",
"_id": "5",
"_score": null,
"_source": {
"text": "text2",
"number": 5
},
"sort": [
5
]
}
]
},
"aggregations": {
"foo": {
"doc_count": 5,
"max-number": {
"value": 5
}
}
}
}