Sort random with must query Elasticsearch

37 Views Asked by At

I want to apply random sort based on bool query and want relevant results with random sorting. Here is the query

{
  "query": {
    "function_score": {
      "random_score": {
        "seed": 100,
        "field": "_seq_no"
      },
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "is_active": true
              }
            }
          ],
          "should": [
            {
              "terms": {
                "sentiment.keyword": [
                  "Negative",
                  "Sad"
                ]
              }
            },
            {
              "terms": {
                "tag.keyword": [
                  "emotions",
                  "mental health",
                  "sadness"
                ]
              }
            }
          ]
        }
      }
    }
  }
}

I have tries using random_score but not sure is it helpful for me or not and anyone know usage of seed?

1

There are 1 best solutions below

3
Musab Dogan On

You can use function score query with random_score option.

GET /_search
{
  "query": {
    "function_score": {
      "query": { "match_all": {} },
      "boost": "5",
      "random_score": {}, 
      "boost_mode": "multiply"
    }
  }
}

The random_score generates scores that are uniformly distributed from 0 up to but not including 1. By default, it uses the internal Lucene doc ids as a source of randomness, which is very efficient but unfortunately not reproducible since documents might be renumbered by merges. https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html#function-random

In case you want scores to be reproducible, it is possible to provide a seed and field. - do you need that?