Search code examples
elasticsearchkibanaelasticsearch-7

Elastic search apply boost only for certain documents based on their field value


Below are my indexed documents:

{
  "id": 123,
  "details": {
    "boostType": "Type1",
    "boostFactor": 1.00022
  }
}
{
  "id": 456,
  "details": {
    "boostType": "Type2",
    "boostFactor": 1.00022
  }
}

So I want to apply boost to only the documents having boostType1 and the boost value will be 1.00022. below is my query but it applies boost to all documents, I want it only for certain boostType. I've tried doing it as follows:

{
  "query": {
    "function_score": {
      "boost_mode": "sum",
      "functions": [
        {
          "field_value_factor": {
            "field": "details.boostFactor",
            "factor": 1,
            "missing": 1
          }
        }
      ]
    }
  }
}

Solution

  • Functions accept additional filter object, read here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html, that should work for you.

    {
      "query": {
        "function_score": {
          "boost_mode": "sum",
          "functions": [
            {
              "filter": {
                "term": {
                  "details.boostType": "Type1"
                }
              }, 
              "field_value_factor": {
                "field": "details.boostFactor",
                "factor": 1,
                "missing": 1
              }
            }
          ]
        }
      }
    }
    

    Note that I've got boostType mapped as a keyword.