DEV Community

Slothy
Slothy

Posted on

Randomize ElasticSearch results with PHP

Simple example of how to re-order your original query and wrap it to randomize the results.

This is using the official PHP ES library: https://github.com/elastic/elasticsearch-php

<?php

if ($this->random) {
    $originalQuery = $this->params['body']['query'];

    $this->params['body']['query'] = [
        'function_score' => [
            'query' => $originalQuery,
            'random_score' => (new \stdClass()),
        ],
    ];
}

$searchRawResult = $this->client->search($this->params);
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
epauli profile image
EPauli • Edited

This is my search data:

array (size=1)
  'function_score' => 
    array (size=2)
      'query' => 
        array (size=1)
          'bool' => 
            array (size=2)
              'must' => 
                array (size=0)
                  empty
              'filter' => 
                array (size=3)
                  0 => 
                    array (size=1)
                      'term' => 
                        array (size=1)
                          'locale' => int 1
                  1 => 
                    array (size=1)
                      'terms' => 
                        array (size=1)
                          'categories' => 
                            array (size=8)
                              0 => int 1256
                              1 => int 1258
                              2 => int 1265
                              3 => int 1267
                              4 => int 1268
                              5 => int 1266
                              6 => int 1264
                              7 => int 1269
                  2 => 
                    array (size=1)
                      'term' => 
                        array (size=1)
                          'pagetype' => string 'article' (length=7)
      'random_score' => 
        object(stdClass)[2005]
Enter fullscreen mode Exit fullscreen mode

Results come up, but unfortunately without random sorting. :-(
When I use this search data as a json object in ElasticVue (a browser based Elasticsearch client) the results are random though.

Collapse
 
epauli profile image
EPauli • Edited

I am looking for a method to sort a search result from Elasticsearch in a random order. Nothing seems to work. I tried your example. No error message comes up, but the sorting doesn't change. It is difficult to debug.

I am using this composer package:
"elasticsearch/elasticsearch":"~7"