Vege Table
Vege Table

Reputation: 13

How to limit number of documents returned for each term in Elasticsearch terms query?

I try to get documents with specified list of terms, like this:

GET /_search
{
    "query" : {
        "terms" : {
            "md5" : ["file_1", "file_2"]
        }
    }
}

Is it possible to limit Elasticsearch results just to one document for each term? So as a result, I should have one document for "file_1", one document for "file_2" and so on.

What I try to accomplish is to get Elasticsearch _id of the most recent document for each term in list. Can I do this in this way or it's necessary to do separate request for each term?

Upvotes: 1

Views: 640

Answers (1)

Jorge
Jorge

Reputation: 161

You have two different ways to get the N documents for each term.

  • One way is by performing one request for each term.

  • The other way is by using the top hits aggregation (see the documentation here).

    GET /_search
    {
        "query" : {
            "terms" : {
                "md5" : ["file_1", "file_2"]
            }
        },
        "aggs": {
            "top-docs": {
                "terms": {
                    "field": "md5",
                    "size": 3
                },
                "aggs": {
                    "top_tag_hits": {
                        "top_hits": {
                            "size" : 1
                        }
                    }
                }
            }
        }
    }
    

Upvotes: 1

Related Questions