RailsにElasticsearchを導入する settingsとmappingsは別々に自由に定義できる

今回はelasticsearch-modelという、RailsにElasticsearchを導入する際に必ず利用するであろうgemについてです。

github.com

本記事はgemの使い方という入門者向けではなく、私自身が実際に悩んでgemのコード読み漁ったことをざっくりとご紹介します。



Elasticsearchを導入する際、形態素解析などの設定を記載するsettingsとmodelの属性をインデクシングする際のmappingsというのを実装するのですが、gemのREADMEに記載されているコードでは、settingsのブロックの中にmappingsを定義しています。

elasticsearch-model#index-configuration

class Article
  settings index: { number_of_shards: 1 } do
    mappings dynamic: 'false' do
      indexes :title, analyzer: 'english', index_options: 'offsets'
    end
  end
end



これだと色々都合が悪い場合があります。

しかし、実際はmappingssettingsのブロックの中に書く必要はありません。

別途moduleを用意して以下のようにsettingsmappingsを別々に書き、modelでincludeすることができます。

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    
    settings index: {
      # ...
      analisys: {
        # ...
      }
    }

    mapping do
      # ...
    end

    def self.search(query)
      # ...
    end
  end
end

#
class Article
  include Searchable
end



別々に書けると何が良いのかは、別記事で紹介したいと思います。