開發環境篇
環境:
- Mac OS X
- 使用 Homebrew
- 使用 rvm, ruby 1.9.3, rails 3.1
安裝 Sphinx
brew install sphinx
安裝 Thinking Sphinx
in Gemfile:
gem 'thinking-sphinx'
然後 bundle install.
設定索引
http://freelancing-god.github.com/ts/en/indexing.html
設定 Thinking Sphinx
首先加入中文支援, in config/sphinx.yml:
development:
ngram_len: 1
ngram_chars: "U+3000..U+2FA1F"
接著執行 rake ts:conf,
這個 task 會產生設定檔 config/[environment].sphinx.conf,
請不要加入 git, 因為這個檔案會包含 database.yml 的資訊,
因此請將它加入 .gitignore.
建立索引
執行 rake ts:index 後會建立索引, 並儲存於 db/sphinx/,
同樣的這個目錄也應該加入 .gitignore.
這個 task 需加入 crontab, 約半小時執行一次.
如果使用 whenever, 可在 config/schedule.rb 中加入:
every(30.minute) { rake 'ts:index' }
啟動 searchd
執行 rake ts:start, 若看到 Started successfully (pid xxxxx).,
表示順利啟動成功.
必須要啟動 searchd 才能進行搜尋, 否則會噴 Riddle::ConnectionError.
注意事項
若有變更資料庫或者索引, 必須執行 rake ts:rebuild 重新建立索引.
生產環境篇
環境:
- Arch Linux
- 使用 yaourt
- 使用 rvm, ruby 1.9.3, rails 3.1
- 使用 Capistrano
安裝 Sphinx
yaourt -S sphinx
設定 Thinking Sphinx
加入中文支援, in config/sphinx.yml:
production:
ngram_len: 1
ngram_chars: "U+3000..U+2FA1F"
設定 Sphinx 執行檔位置, in config/sphinx.yml:
production:
ngram_len: 1
ngram_chars: "U+3000..U+2FA1F"
bin_path: /usr/bin/
searchd_binary_name: sphinx-searchd
indexer_binary_name: sphinx-indexer
設定 Capistrano
在 config/deploy.rb 中加入:
namespace :deploy do
namespace :thinking_sphinx do
task :stop, :roles => :app do
run "cd #{current_path} && RAILS_ENV=#{rails_env} bundle exec rake ts:stop"
end
task :restart, :roles => :app do
run "cd #{release_path} && RAILS_ENV=#{rails_env} bundle exec rake ts:stop ts:rebuild"
end
end
before 'deploy:update_code', 'deploy:thinking_sphinx:stop'
after 'deploy:restart', 'deploy:thinking_sphinx:restart'
end
第一次 deploy 時得先拿掉 before 'deploy:update_code', 'deploy:thinking_sphinx:stop',
因為這個時候還沒有安裝 Thinking Sphinx, 會找不到 ts:stop 這個 rake task.
順便一提 ts:rebuild 也會順便把 searchd 開起來, 所以就不用再跑 ts:start 了.