Search code examples
rankingelasticsearch

Does ElasticSearch support define fixed ranking strategy?


Everytime I use the same query, such as code below:

{
"bool": {
    "should": [
        {
          "multi_match" : {
            "query":      "Will Smith",
            "type":       "cross_fields",
            "fields":     [ "first", "last" ],
            "minimum_should_match": "50%" 
          }
        },
        {
          "multi_match" : {
            "query":      "Will Smith",
            "type":       "cross_fields",
            "fields":     [ "*.edge" ]
          }
        }
    ]
}}

Each time I use different query word, but the params are the same.

Does elasticsearch support this kind of strategy we can define, like ranking strategy? Each time I just need to input the query.


Solution

  • Elasticsearch supports template query where you can register a query and pass the query string as a param

    Example:

    1. Create a .scripts index if it doesn't exists
    PUT <server::port>/.scripts
    
    1. Register the query template for the above case
     PUT <server::port>/_search/template/<template_name>
     {    
      "template": {
      "query": {
         "bool": {
            "should": [
               {
                  "multi_match": {
                     "query": "{{query_string}}",
                     "type": "cross_fields",
                     "fields": [
                        "first",
                        "last"
                     ],
                     "minimum_should_match": "50%"
                  }
               },
               {
                  "multi_match": {
                     "query": "{query_string}",
                     "type": "cross_fields",
                     "fields": [
                        "*.edge"
                     ]
                  }
               }
            ]
         }
      }    
    

    } }

    1. Invoke search template with query_string param
     POST <server::port>/index>/_search/template {    
        "template": {
            "id": "<template_name>"    
        },    
        "params": {
            "query_string": "will smith"    
        }      
     }