|
| 1 | +# Description: |
| 2 | +# Include this module in models that should be searchable. |
| 3 | +# |
| 4 | +# Models including the concern are expected to implement 'title' and 'searchable_content' |
| 5 | +# for indexing. Title will be given higher priority compared to content. |
| 6 | +# |
| 7 | +# After adding and indexing your models. Search across all models can be performed via |
| 8 | +# the Searchable.search method. |
| 9 | + |
| 10 | +module Searchable |
| 11 | + extend ActiveSupport::Concern |
| 12 | + |
| 13 | + mattr_accessor :models |
| 14 | + self.models = [] |
| 15 | + |
| 16 | + def self.search(query) |
| 17 | + return [] if query.blank? |
| 18 | + |
| 19 | + search_definition = { |
| 20 | + query: { |
| 21 | + multi_match: { |
| 22 | + query: query, |
| 23 | + fields: ["title^2", "content"], |
| 24 | + }, |
| 25 | + }, |
| 26 | + } |
| 27 | + |
| 28 | + Elasticsearch::Model.search(search_definition, models).records |
| 29 | + end |
| 30 | + |
| 31 | + def as_indexed_json(_options = {}) |
| 32 | + { |
| 33 | + title: title, |
| 34 | + content: searchable_content, |
| 35 | + } |
| 36 | + end |
| 37 | + |
| 38 | + def should_index? |
| 39 | + true |
| 40 | + end |
| 41 | + |
| 42 | + def searchable_content |
| 43 | + raise NotImplementedError |
| 44 | + end |
| 45 | + |
| 46 | + included do |
| 47 | + include Elasticsearch::Model |
| 48 | + |
| 49 | + Searchable.models << self |
| 50 | + |
| 51 | + after_commit on: :create, if: :should_index? do |
| 52 | + IndexerJob.perform_later("create", self.class.name, id) |
| 53 | + end |
| 54 | + |
| 55 | + after_commit on: :update, if: :should_index? do |
| 56 | + IndexerJob.perform_later("update", self.class.name, id) |
| 57 | + end |
| 58 | + |
| 59 | + after_commit on: :destroy do |
| 60 | + IndexerJob.perform_later("delete", self.class.name, id) |
| 61 | + end |
| 62 | + |
| 63 | + settings index: { number_of_shards: 1 } do |
| 64 | + mappings dynamic: "false" do |
| 65 | + indexes :title, analyzer: "english", boost: 2 |
| 66 | + indexes :content, analyzer: "english" |
| 67 | + end |
| 68 | + end |
| 69 | + end |
| 70 | +end |
0 commit comments