elasticsearch

Scoring elasticsearch query by date with linear function and constant score

Published at 2015-11-29

In one of our recent projects, my development team was asked about the possibility to score search results sorely based on dates. The query must:

Using linear function and constant score

We decided to let a constant score query detect the query in selected fields (title, body). This will always return the same/constant score. After all relevant documents have matched, we use a linear function to affect the score. We have set this to decay for four years (104 weeks / 0.5 decay).

This is our finished query:

{
    "query": {
      "function_score": {
        "functions": [
          {
            "linear": {
              "updated": {
                "origin": "now",
                "scale": "104w",
                "decay": 0.5
              }
            }
          }
        ],
        "query": {
          "constant_score": {
            "query": {
              "bool": {
                "should": [
                  {
                    "match_phrase": {
                      "title": {
                        "query": "{{query}}"
                      }
                    }
                  },
                  {
                    "match_phrase": {
                      "body": {
                        "query": "{{query}}"
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }
    }
  }

This is an implementation for ElasticSearch 1.5. Might be outdated for future implementations.

Avatar of Author

Karl SolgÄrd

Norwegian software developer. Eager to learn and to share knowledge. Sharing is caring! Follow on social: Twitter and LinkedIn. Email me: [email protected]