Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch: how to rank-high the exact match?

I want to search item "vision" for one field but I just got results like "vision A", "vision B", "xx version","vision" etc by using match/match_phrace/term in the DSL.

What I want is the exact match "vision" should have the highest score and the items which contain "vision" should rank behind the exact match. The ranking should be:

vision > vision A > vision B > xx version

I checked Elasticsearch match exact term in which change the "index" to be "not_analyzed" is recognized to realize exact match. But in my case not only exact match but also the containing match is needed.

What can I do for this case? Thanks!

like image 477
Elva Avatar asked Dec 17 '22 20:12

Elva


1 Answers

What you can do to achieve this is to include a few constraints in q bool/should query in order to control the ranking.

{
  "query": {
    "bool": {
      "must": {
        "match": {
          "name": "vision"                  <--- match on vision
        }
      },
      "should": [
        {
          "term": {
            "name.keyword": {               <--- boost exact matches on keyword field (i.e. "vision")
              "value": "vision",
              "boost": 3
            }
          }
        },
        {
          "prefix": {
            "name.keyword": {               <--- boost prefix matches on keyword field (i.e. "vision A" and "vision B"
              "value": "vision",
              "boost": 2
            }
          }
        }
      ]
    }
  }
}
  • The first clause will match all documents which contain vision in their name field.
  • The second clause will give a higher boost to documents whose name.keyword field contains exactly vision. name.keyword is usually a keyword field (formerly a not_analyzed string field).
  • The third clause will give a slightly higher boost to documents whose name.keyword field starts with vision.
like image 147
Val Avatar answered Jan 13 '23 13:01

Val