0

I have my elasticsearch query that returns record between the range of publishedDates:

{
  query : {
    bool: {
      filter: [

      ],
      must: {
        range: {
          publishedDate: {
            gte: "2018-11-01",
            lte: "2019-03-30"
          }
        }
      }
    }
  }
  from: 0,
  size: 3,
}

I need to show 3 random results every time I send this query

It is mentioned in the elastic search documentation that I can send a seed to get random results:

After following the documentation, I updated my query as:

{
  "query" : {
    "bool": {
      "filter": [

      ],
      "must": {
        "range": {
          "publishedDate": {
            "gte": "2018-11-01",
            "lte": "2019-03-30"
          }
        }
      }
    },
    "function_score": {
      "functions": [
        {
          "random_score": {
            "seed": "123123123"
           }
        }
      ]
    }
  },
  "from": 0,
  "size": 3
}

But it is not working (saying query is malformed), can anyone suggest how to correct this query to return 3 random search results.

Bharthan
  • 1,458
  • 2
  • 17
  • 29

1 Answers1

1

If you just need random results returned, you could restructure the query to be similar to the following

{
  "query": {
    "function_score": {
      "query": {
        "range": {
          "publishedDate": {
            "gte": "2018-11-01",
            "lte": "2019-03-30"
          }
        }
      },
      "boost": "5",
      "random_score": {},
      "boost_mode": "multiply"
    }
  },
  "from": 0,
  "size": 3
}

Modified from the elastic documentation - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html

kjr
  • 131
  • 4
  • Thanks, it solved my problem. Can you suggest what is the need of `boost` and `boost_mode` here... I see in documentation it is used to affect score somehow. – Bharthan Mar 22 '19 at 11:29
  • They probably aren't needed in this case, `multiply` is the default value for `boost_mode` (and there's only a single function anyway) – kjr Mar 22 '19 at 12:03