i_have_question
i_have_question

Reputation: 3

How to boost specific terms in elastic search?

If I have the following mapping:

PUT /book
{
  "settings": {},
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      },
      "author": {
        "type": "text"
      }
    }
  }
}

How can i boost specific authors higher than others? In case of the below example:

PUT /book/_doc/1
{
  "title": "car parts",
   "author": "john smith"
}

PUT /book/_doc/2
{
  "title": "car",
   "author": "bob bobby"
}

PUT /book/_doc/3
{
  "title": "soap",
   "author": "sam sammy"
}

PUT /book/_doc/4
{
  "title": "car designs",
   "author": "joe walker"
}

GET /book/_search
{
   "query": {  
      "bool": {                    
        "should": [
             { "match": { "title": "car" }},
              { "match": { "title": "parts" }} 
         ]
       }
   }
}

How do I make it so my search will give me books by "joe walker" are at the top of the search results?

Upvotes: 0

Views: 72

Answers (1)

Assael Azran
Assael Azran

Reputation: 2993

One solution is to make use of function_score.

The function_score allows you to modify the score of documents that are retrieved by a query.

From here

Base on your mappings try to run this query for example:

GET book/_search
{
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "should": [
            {
              "match": {
                "title": "car"
              }
            },
            {
              "match": {
                "title": "parts"
              }
            }
          ]
        }
      },
      "functions": [
        {
          "filter": {
            "match": {
              "author": "joe walker"
            }
          },
          "weight": 30
        }
      ],
      "max_boost": 30,
      "score_mode": "max",
      "boost_mode": "multiply"
    }
  }
}

The query inside function_score is the same should query that you used.

Now we want to take all the results from the query and give more weight (increase the score) to joe walker's books, meaning prioritize its books over the others.

To achieved that we created a function (inside functions) that compute a new score for each document returned by the query filtered by joe walker books.

You can play with the weight and other params.

Hope it helps

Upvotes: 0

Related Questions