简体   繁体   中英

custom query with sunspot solr on rails 3.2

3 models:

Class Product
 include Mongoid::Document
 has_many :orders, dependent: :destroy, :autosave => true
 #search
 searchable do
  text :title, :description, :boost => 2.0
  time :created_at
 end
end

Class Order
 include Mongoid::Document
 belongs_to :product
 has_one :dispute, dependent: :destroy, :autosave => true
end

Class Dispute
 include Mongoid::Document
 belongs_to :order
 field :buyer_has_requested_refund, :type => Boolean, :default => "false"
end

I need inside products_controller.rb on index action, get and sort high to low all products with orders have disputes with buyer_has_requested_refund = true

Something like:

def index
 @search = Product.solr_search do |s|
 s.fulltext params[:search]
 s.keywords params[:search]
 s.order_by :disputes_where_buyer_has_requested_refund, :desc
 end
 @products = @search.results
    respond_to do |format|
    format.html # index.html.erb
  end 
end

Thank you!

You should tell solr to index the information you need for sorting the search:

class Product
 include Mongoid::Document
 has_many :orders, dependent: :destroy, :autosave => true
 has_many :disputes, :through => :orders
 #search
 searchable do
  text :title, :description, :boost => 2.0
  integer :disputes_where_buyer_has_requested_refund { |product| product.disputes.where(:buyer_has_requested_refund => true).size }
  time :created_at
 end
end

Be aware of reindexing the record value in the index accordingly when new disputes are created/destroyed. You could do that with after_create/after_destroy hooks in a delayed job or also reindex once a day depending on your needs and the size of your index.

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