Home > Mobile >  Boost result which has the current date in between dates
Boost result which has the current date in between dates

Time:06-03

My mapping has two properties:

"news_from_date" : {
    "type" : "string"
},
"news_to_date" : {
    "type" : "string"
},

Search results have the properties news_from_date, news_to_date

curl -X GET 'http://172.2.0.5:9200/test_idx1/_search?pretty=true' 2>&1 

Result:

{
    "news_from_date" : "2022-05-30 00:00:00",
    "news_to_date" : "2022-06-23 00:00:00"
}

Question is: How can I boost all results with the current date being in between their "news_from_date"-"news_to_date" interval, so they are shown as highest ranking results?

CodePudding user response:

Tldr;

First off if you are going to play with dates, you should probably use the one of the dates type provided by Elasticsearch.

They are many way to approach you problem, using painless, using scoring function or even more classical query types.

Using Should

Using the Boolean query type, you have multiple clauses.

  • Must
  • Filter
  • Must_not
  • Should

Should allow for optionals clause to be factored in the final score.

So you go with:

GET _search
{
  "query": {
    "bool": {
      "should": [
        {
          "range": {
            "news_from_date": {
              "gte": "now"
            }
          }
        },
        {
          "range": {
            "news_to_date": {
              "lte": "now"
            }
          }
        }
      ]
    }
  }
}

Be aware that:

You can use the minimum_should_match parameter to specify the number or percentage of should clauses returned documents must match.

If the bool query includes at least one should clause and no must or filter clauses, the default value is 1. Otherwise, the default value is 0.

Using a script

As provided by the documentation, you can create a custom function to score your documents according to your own business rules.

The script is using Painless (a stripped down version of java)

GET /_search
{
  "query": {
    "function_score": {
      "query": {
        "match": { "message": "elasticsearch" }
      },
      "script_score": {
        "script": {
          "source": "Math.log(2   doc['my-int'].value)"
        }
      }
    }
  }
}
  • Related