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:

  • Detect documents that contain the search query
  • Score documents with a newer updated date higher

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.