Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elasticsearch customize score for synonyms/stemming

I am using elasticsearch 1.1.2.

I am using multimatch query with different weights on the searchable fields.

Example:

{ "multi_match" : { "query" : "this is a test", "fields" : [ "title^3", "description^2", "body" ] } }

So here in my example title is three times as important as the body.

I would like to customize the weight given for each field depending on the match found.

Let's say I search for "injury", I want to:

-Give the title a coefficient of 3 if an exact match is found: title contains the word "injury".

-Give the title a coefficient of 2 if a synonym is found: title contains the word "bruise".

-Give the title a coefficient of 1 if a stemming is found : title contains the word "injuries".

Is there a way to do this kind of customization ?

Thanks!

like image 270
Zied Koubaa Avatar asked Feb 03 '15 17:02

Zied Koubaa


1 Answers

You can achieve that by using a multi-fields mapping on your title value.

It allows you to map several types, and so to use different analyzers, to the same input value.

Assuming you have defined custom analyzers for both synonym and stemming, try to update your mapping :

PUT /<index_name>/<type_name>/_mapping
{
  "<type>": {
    "properties": {
      "title": {
        "type": "string",
        "fields": {
          "exact": {
            "type": "string",
            "index": "not_analyzed"
          },          
          "synonym": {
            "type": "string",
            "index": "analyzed",
            "analyzer": "synonym_analyzer"
          },
          "stemmed": {
            "type": "string",
            "index": "analyzed",
            "analyzer": "stemming_analyzer"
          }
        }
      }
    }
  }
}

And the following query should match as you wish :

POST /<index_name>/<type_name>/_search
{
  "query": {
    "multi_match": {
      "query": "injury",
      "fields": [
        "title.exact^3",
        "title.synonym^2",
        "title.stemmed"
      ]
    }
  }
}
like image 95
ThomasC Avatar answered Oct 02 '22 10:10

ThomasC