Home > Software design >  Elasticsearch query different fields with different weight
Elasticsearch query different fields with different weight

Time:10-07

Say I have 3 different fields, A of text type, B of int type, C of date type. I other query conditions for all 3 fields. In addition to this, I want to give more weightage to field C then B then A. ie A is looking for text having word 'xyz' and it haves less priority,say weight of 1 B is looking for values greater than 100 and it have some priority, say weight of 5 and C should have a date greater than June 2022 and it has a higher priority of weight 10.

How do I write an es query to perform this

CodePudding user response:

You can boost your queries. Check this links:

Elasticsearch 8.4

Elasticsearch 7.17

hope this helps to construct your queries.

CodePudding user response:

Here is your query. Please test against your data and check if this query completing your requirement.

GET index-name/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "function_score": {
            "functions": [
              {
                "filter": {
                  "multi_match": {
                    "query": "search-text",
                    "fields": [
                      "field-A"
                    ]
                  }
                },
                "weight": 1
              },
              {
                "filter": {
                  "range": {
                    "field-B": {
                      "gt": 100
                    }
                  }
                },
                "weight": 5
              },
              {
                
                "filter": {
                  "range": {
                    "field-C": {
                      "gte": "2022-06-01"
                    }
                  }
                },
                "weight": 10
              }
            ],
            "score_mode": "max",
            "boost_mode": "replace"
          }
        }
      ]
    }
  },
  "_source": ["field-A", "field-B", "field-C"]     ----> if you want verify with limited fields
}
  • Related