Random sort


I have index with 25 000 documents which are looks like:

GET locations/location/10/_source
  "country_code": "US",
  "id": "10",
  "continent_code": "NA",
  "city_name": "New York"

I need to get some random cities from two continents, so I'm using this request:

POST locations/_search
  "query" : {
      "function_score" : {
         "query" : {
            "bool" : {
               "filter" : {
                  "query_string" : {
                     "query" : "(continent_code:af and continent_code:eu)"
         "random_score": {}

But all cities in response are from EU. AF cities are really exists. I can see them with continent_code:af only without continent_code:eu.

Please explain me why I see so strange results and how to see EU and AF cities in random order.

This looks funky. I'd remove the word "and" here as it will be a free-text search for the string "and".
Normally the query score and the random score will be multiplied together. To get a pure random score you need to replace the query score with the output of the random score. Do this by adding:


Thank you for "boost_mode" but this is not exact what I need. I more general form requests from my application will contain 2 types of criteria:

  • Mandatory filter by continent/country
  • Optional More Like This part, which must be applied if possible (e.g. if additional fields exists)

Results must be sorted in random order if optional part was not applied, but optional part must have more priority over random order while sorting if possible.

It will be simple for me to implement mandatory filter as query_string (which can contain AND and OR - see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html), and I know about weight parameter of score function, but I can't understand how to set 0 weight for mandatory filter, 1 for random sorting and 9 for optional part with More Like This query.

Can you show me example?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.