Rails
solr

Railsでsunspot(solr)を使って全文検索

More than 5 years have passed since last update.


インストールから起動まで


Gemfile

gem 'sunspot_rails'

gem 'sunspot_solr'


コンフィグファイルを生成

rails generate sunspot_rails:install



solrを起動

bundle exec rake sunspot:solr:start



既存のデータに対して再Index

modelのsearchableを見てるので

searchableの内容を変更した時も実行しないといけないみたい


Indexを再作成

bundle exec rake sunspot:solr:reindex



検索

基本的な使い方


model

has_many :bookmarks

searchable do
text :title
text :content
double :rating
integer :user_id

string :tags, :multiple => true do
bookmarks.map {|b| b.tag}
end
end



controller

result = Recipe.search do

fulltext params[:q]
end
@recipes = result.results

withで追加条件を指定可能


controller

result = Recipe.search do

fulltext params[:q]

with :rating, 1
with :user_id, user_id if user_id.present?
end
@recipes = result.results


様々な条件指定


controller

with :rating, 1 # rating = 1

with(:rating).less_than 1 # rating < 1
with(:rating).less_than_or_equal_to 1 # rating <= 1
with(:rating).greater_than 1 # rating > 1
with(:rating).greater_than_or_equal_to 1 # rating >= 1

multipleなFieldに対する条件指定


controller

with :tags, [1, 2] # 1 or 2

with(:tags).all_of [1, 2] # 1 and 2

ページングも出来る


controller

result = Recipe.search do

fulltext params[:q]

with :user_id, user_id if user_id.present?
paginate :page => 1, :per_page => 10
end
@recipes = result.results