Emixam23
Emixam23

Reputation: 3964

ElasticSearch - How can i apply a filter over the results of the query to limit the document that have a certain value

I have a question regarding elastic search but I am not sure where to start searching or which precise operation I should search for using google.

Let say I have a document with data and one of its fields is "the_best" (which is a boolean). The thing is (currently), over 48 results (given by a working query), I have like 15 documents returned with the_best field set to true.

Now, I would like to limit this by only 2 maximum documents set to true over the results. So now, it (elasticsearch) should now return 35 results (if we stik at the story above):

Any idea? :)

Upvotes: 1

Views: 1520

Answers (1)

jaspreet chahal
jaspreet chahal

Reputation: 9099

One way to do is using m_search

using m_Search you can combine multiple queries

GET <index>/_msearch
{}
{"query":{"term":{"the_best":true}},"from":0,"size":2}
{}
{"query":{"term":{"the_best":false}},"from":0,"size":15}

If you want to do it in single search aggregation can be used(will be less performant)

I have used filter aggregation and top_hits aggregation

{
  "size": 0, 
  "aggs": {
    "true": {
      "filter": {
        "term": {
          "the_best": true
        }
      },
      "aggs": {
        "docs": {
          "top_hits": {
            "size": 2
          }
        }
      }
    },
    "false": {
      "filter": {
        "term": {
          "the_best": false
        }
      },
      "aggs": {
        "docs": {
          "top_hits": {
            "size": 10
          }
        }
      }
    }
  }
}

Upvotes: 2

Related Questions