サンプル用に新しいRailsアプリケーションを作成します。
$ cd $ rails new book $ cd book
sunspotは、EnjuをはじめとするRuby on RailsアプリケーションでSolrを使用するためのライブラリです。
sunspotを読み込みます。Gemfileを開き、以下の行を追加します。
$ vi Gemfile
# 以下の2行を追加 (「gem 'sqlite3'」の下あたりに) gem 'sunspot_rails' gem 'sunspot_solr'
$ bundle update # ライブラリの読み込み
アプリケーションのひな形を作ります。
$ rails g scaffold Manifestation original_title:string note:text
sunspotの設定ファイルを作成します。
$ rails g sunspot_rails:install
設定ファイルを開き、Solrのポート番号を変更します(同一マシンでの実習のため)。
$ vi config/sunspot.yml
production:
solr:
hostname: localhost
port: 8983 # これを変更
log_level: WARNING
development:
solr:
hostname: localhost
port: 8982 # これを変更
log_level: INFO
test:
solr:
hostname: localhost
port: 8981
log_level: WARNING
sunspotを使用する設定をモデルに追加します。
$ vi app/models/manifestation.rb
class Manifestation < ActiveRecord::Base
# 以下の行を追加
searchable do
text :original_title
text :note
end
end
データベースを作成します。
$ rake db:migrate
Solrを起動します。今回はsunspotに同梱されているSolrを使用します。
$ rake sunspot:solr:start
Railsアプリケーションを起動します。ポート番号( -p 3001 )などは指定したものに変更してください。
$ rails s -p 3001
ここでWebブラウザを開いてください。ポート番号は適当に変更してください。
- http://192.168.11.5:3000/manifestations (ポート番号は適宜変更する)
ビューにフォームを追加します。app/views/manifestations/index.html.erb に以下の行を追加します。
$ vi app/views/manifestations/index.html.erb
<%= form_tag manifestations_path, :method => :get do %> <%= text_field_tag :query, params[:query] %> <%= submit_tag "Search" %> <% end %>
コントローラに検索ロジックを追加します。
$ vi app/controllers/manifestations_controller.rb
def index
# 以下の行をコメントアウト
# @manifestations = Manifestation.all
# 以下の3行を追加
@manifestations = Manifestation.search do
fulltext params[:query] # ビューで追加したtext_field_tagと同じ名前を用いる
end.results
(以下略)
end
ここまでで設定は完了です。Webブラウザで自分のアプリケーションのURL( http://192.168.11.5:3000/manifestations など;ポート番号は指定のものに変える)開き、適当にデータを追加したあと、検索フォームで検索を行ってみてください。
solr/conf/schema.xml を以下のように編集します。
<fieldType name="text" class="solr.TextField" omitNorms="false">
<analyzer>
<tokenizer class="solr.CJKTokenizerFactory"/>
<!--
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.StandardFilterFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
-->
</analyzer>
</fieldType>
変更後、solrを再起動します。
$ rake sunspot:solr:stop $ rake sunspot:solr:start
インデックスを再度作成します。
$ rake sunspot:reindex
