Search code examples
ruby-on-railselasticsearchsearchkick

Fetching results in random order with a :where clause using searchkick and rails


This is probably a simple thing, but I can't seem to get my head around it:

I want elasticsearch to return:

@random_books   = Book.search("*", where: { status: :published }, body: { query: { function_score: { random_score: { seed: seed }}}}, page: params[:page], per_page: 12)

The results returned do not honor the where: {status: :published} clause. How do I syntax up this query?

Edits: Found another question asking basically the same thing; without a working solution/answer of course.


Solution

  • Okay, here's the solution:

    seed = Time.zone.now.to_i
    
    @random_books   = Book
                        .search("*",
                          body: {
                            query: {
                              function_score: {
                                query: {
                                  match: { status: :published }
                                  },
                                random_score: {
                                  seed: seed
                                }
                              }
                            }
                          },
                          page: params[:random],
                          per_page: 12)
    

    Searchkick will ignore the options (like where: clause) if we pass body to elasticsearch. So we match the query inside of function_score as described here.

    Easy-peasy.