Limit number of documents returned by each clause in Search query

I have a category field in my documents, which is mapped as a keyword. I am trying to run a search query that fetches the latest n documents for each category specified in the query.

I am able to achieve this using a multi-search, with each term search looking for the latest n documents for a particular category, but I was wondering if it possible to achieve using a single search query.

I have drafted a bool query that illustrates this problem:

curl -X GET "http://localhost:9200/my_index_2019-09-08,my_index_2019-09-07/_search?pretty" -H 'Content-Type: application/json' -d '
{
    "_source": ["category", "field1", "field2", "field3"],
    "query": {
        "bool": {
            "should": [
                {"term": {"category": "green"}},
                {"term": {"category": "blue"}}
            ],
            "minimum_should_match" : 1
        }
    },
    "sort": [{"field3": "desc"}],
    "from": 0,
    "size": 10
}
'

This query fetches the latest 10 documents that match either category. Ideally, I would like to be able to limit the number of matches for each category, if possible.

Elasticsearch version: 6.5.4

See Top Hits Aggs

It worked really well, thanks! I was able to rewrite my query in the following manner:

curl -X POST "http://localhost:9200/my_index_2019-09-08,my_index_2019-09-07/_search?size=0&pretty" -H 'Content-Type: application/json' -d'
{
    "aggs": {
        "top_tags": {
            "terms": {
                "field": "category",
                "include": ["green", "blue"]
            },
            "aggs": {
                "category": {
                    "top_hits": {
                        "sort": [{"field3": "desc"}],
                        "_source": {
                            "includes": [
                                "field1", "field2", "field3", "category"
                            ]
                        },
                        "size" : 1
                    }
                }
            }
        }
    }
}
'

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.