Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Boost a field based on condition in ElasticSearch

I am having a query structure like

{
  "sort": {},
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "user_categories": "Grant Writing"
          }
        },
        {
          "match_phrase": {
            "user_agencies": "Census"
          }
        },
        {
          "match_phrase": {
            "user_agencies": "MDA"
          }
        },
        {
          "match_phrase": {
            "user_agencies": "OSD"
          }
        }
      ]
    }
  },
  "size": 500,
  "from": 0
}

Suppose this will return a list of 10 users.

What I need to get is, the user having Agency: 'Census' to be the first one in the search result (boost the results having Census as agency). How can we do this?

like image 538
Amal Kumar S Avatar asked Sep 04 '25 17:09

Amal Kumar S


1 Answers

The following will do it. I converted some of the match_phrase queries to match queries as they contain only single terms

{
  "sort": {},
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "user_categories": "Grant Writing"
          }
        },
        {  
          "match": {
            "user_agencies": { 
              "query": "Census",
              "boost": 3
            }
          }
        },
        {
          "match": {
            "user_agencies": {
              "query": "MDA",
          }
        },
        {
          "match": {
            "user_agencies": {
              "query": "OSD",
          }
        }
      ]
    }
  },
  "size": 500,
  "from": 0
}
like image 178
Russ Cam Avatar answered Sep 07 '25 12:09

Russ Cam