Elasticsearch random scoring with filters


(Andy) #1

I've got a situation, using ES 6.2, where I can either perform a bool or a random_score , but not both at the same time. Here is one of those potential queries:

{
  "from": 0,
  "size": 50,
  "query": {
    "function_score": {
      "random_score": {
        "seed": 10,
        "field": "_seq_no"
      }
    },
    "bool": {
      "filter": [
        {
          "terms": {
            "primary_category": [
              "foobar"
            ]
          }
        },
        {
          "terms": {
            "primary_type": [
              "barbaz"
            ]
          }
        }
      ]
    }
  }
}

If I were to remove either the function_score block or the bool block, the query works, but in combination, it does not:

[function_score] malformed query, expected [END_OBJECT] but found [FIELD_NAME]

Am I missing something about the example at: https://www.elastic.co/guide/en/elasticsearch/reference/6.2/query-dsl-function-score-query.html#function-random

All I want to do is "randomly sort" my results in a predictable way which will work across pagination, etc. Really I am just trying to display the filtered results with high variance, as any sort of standard sorting will create patterns in the result which I am trying to avoid.

Any help would be appreciated, and I'll keep tinkering with it.


(Ryan Ernst) #2

The query element of a search request can only have one sub-object. You likely want to put the bool query inside the function_score query under the query element there.