Search code examples
elasticsearchrelevancefunction-query

Function_score using score_mode inside a bool query as max but working like sum?


I am using function_score so that i can use its score_mode as maximum score of the bool query i am using actually i have two boolean query inside should now i want the score of the document to be the maximum score among both queries my code is given below but when i am passing a string for matching both then scores are being added not be taken maximum can anyone please tell me how can i acheive that.

"function_score": {
      "boost_mode": "max",
      "score_mode": "max",
      "query": {
        bool: {
          "disable_coord": true,
          "should": [
            {
              bool: {
                "disable_coord": true,
                "must": [
                  {
                    "constant_score": { // here i am using this because to remove tf/idf factors from my scoring
                      boost: 1.04,
                      "query": {
                        query_string: {
                          query: location_search,
                          fields: ['places_city.city'],
          //               boost: 1.04
                        }
                      }
                    }
                  }
                ]
              }
            },
            {
              "constant_score": { // here i am using this because to remove tf/idf factors from my scoring
              boost: 1,
                "query": {
                  "fuzzy_like_this" : {
                    "fields" : ["places_city.city"],
                    "like_text" : "bangaloremn",
                    "prefix_length": 3,
                    "fuzziness": 2
                  }
                }
              }
            }
         ], "minimum_should_match": 1
       }
     }
  }    

Solution

  • Yes boolean query takes a sum by design. If you want the maximum score of two queries, you ought to look at the dismax query. Dismax is designed to pick a "winner".

    Roughly speaking, this would look like

    {"query":
        "dismax": {
            "queries": [
                 { /* your first constant_score query above */},
                 {/* your second constant_score query from above */}
            ]
        }
    }
    

    Unfortunately, function score query doesn't have a great way of operating on more than one text query at a time. See this question. If you want to do any complex math with the scores of multiple queries, Solr actually has a lot more flexibility in this area.