简体   繁体   中英

Sorting search results with mongoid-elasticsearch gem

I am trying to implement sorting into my search. I am searching with use of the gem mongoid-elasticsearch . This is my model configuration:

class ActivityLog
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Elasticsearch
  elasticsearch!(
    {
      wrapper: :load,
      sort: [
        { created_at: "desc" }
      ]
    }
  )

  field :type, type: String
end

This configuration does not raise any errors, but it does not either seem like it has any effect, because search results are listed randomly.

I think I am implementing the configuration in accordance to the documentation:

Check mongoid-elasticsearch documentation here

Check elasticsearch documentation here

My search query btw is:

ActivityLog.es.search(params[:query], page: params[:page]).results.paginate(per_page: 5, page: params[:page])

You should remove Array wrapper:

elasticsearch!(
  {
    wrapper: :load,
    sort: { created_at: "desc" }
  }
)

The same way you would do it in Elasticsearch itself

ActivityLog.es.search({
  body: {
    query: {
      query_string: {
        query: params[:search]
      }
    },
    sort: [
        {created_at: {order: "asc"}},
    ]
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM