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