使用 :where 子句使用 searchkick 和 rails 以随机顺序获取结果

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

这可能是一件简单的事情,但我似乎无法理解它:

我希望 elasticsearch return:

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

results returned 不遵守 where: {status: :published} 条款。我该如何语法化这个查询?

编辑:发现 another question 问的基本上是同一件事;当然没有工作solution/answer。

请像这样替换您的 where 子句:

where: { 'status IN(?)', ['published'] }

好的,这是解决方案:

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 将 ignore the options (like where: clause) if we pass body to elasticsearch. So we match the query inside of function_score as described here

简单易行。