RailsにElasticsearchを導入する modelごとにmappingsを実装する
上記の記事で、Elasticsearch-modelのsettingsとmappingsはREADME記載例通りではない書き方ができることを紹介しました。
本記事ではこれの何が良いのかご紹介します。
settingsをベースmoduleにまとめる
以下のように、settingsだけ記載したmoduleを用意します。settingsには形態素解析のプラグインの設定内容などアプリケーション全体で共通の設定を記載すると思うので、個別のmodel用に用意したmoduleに記載するのは面倒です。
settingsだけでなく、まとめたい共通処理があればこちらのmoduleに書いておきます。
module Searchable extend ActiveSupport::Concern included do include Elasticsearch::Model settings index: { # ... analysis: { # ... } } end end
modelごとにmappingsとその他メソッドを
modelごとのmoduleでは、上記で作成したベースmoduleをincludeし、model固有のmappingsやas_indexed_json、検索クエリーなどを定義します。
mappingsや検索クエリーはmodelごとに異なる場合が多いと思いますので、このように分けると実装しやすいです。
module ArticleSearchable extend ActiveSupport::Concern included do include Elasticsearch::Model include Searchable index_name # ... def as_indexed_json(options={}) # ... end end class_methods do def search(text) # ... end end end
上記のmodelごとmoduleをmodelでincludeすればOKです。