# Can this query be optimized?

**URL:** <https://discuss.elastic.co/t/can-this-query-be-optimized/53554>\
**Category:** Elasticsearch\
**Created:** [June 21, 2016, 6:31pm UTC](https://discuss.elastic.co/t/can-this-query-be-optimized/53554 "2016-06-21T18:31:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![wsd](https://avatars.discourse-cdn.com/v4/letter/w/e47774/32.png) [@wsd](https://discuss.elastic.co/u/wsd)\
**Post date:** [June 21, 2016, 6:31pm UTC](https://discuss.elastic.co/t/can-this-query-be-optimized/53554/1 "2016-06-21T18:31:35Z")

</div>

I'm interested in any optimizations, but in particular, I want to ensure the score functions are only executed on documents that match at least one of the should clauses, not on all documents. Not sure whether that is the case as it is written now:

```auto
{
  "body": {
    "query": {
      "function_score": {
        "functions": [
          ...a bunch of functions
        ],
        "boost_mode": "replace",
        "query": {
          "bool": {
            "should": [
              {
                "match_phrase": {
                  "field 1": "query"
                }
              },
              {
                "match_phrase": {
                  "field 2": "query"
                }
              },
              {
                "match_phrase": {
                  "field 3": "query"
                }
              }
            ]
          }
        }
      }
    }
  }
}

```

Elasticsearch \>=2.1, in case it makes a difference.

---

<div class="post-metadata">

**Author:** ![polyfractal](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/polyfractal/32/48162_2.png) [@polyfractal](https://discuss.elastic.co/u/polyfractal)\
**Post date:** [June 21, 2016, 8:02pm UTC](https://discuss.elastic.co/t/can-this-query-be-optimized/53554/2 "2016-06-21T20:02:38Z")

</div>

Your query is correct: the functions will only be evaluated on documents that match at least one of those should clauses (because you only have should clauses, at least one _must_ match to be considered a hit).

The `query` section of the `function_score` is essentially a gatekeeper: only documents that match the query are subsequently scored by the functions. Each function can have it's own filter as well, to further limit what functions are applied to which documents/values.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:41pm UTC](https://discuss.elastic.co/t/can-this-query-be-optimized/53554/3 "2017-07-05T22:41:39Z")

</div>


