Module: SwitchSearchable::SearchEngine::Elasticsearch::ClassMethods

Defined in:
lib/switch_searchable/search_engine/elasticsearch.rb

Instance Method Summary collapse

Instance Method Details

#init_search_engine(*names) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/switch_searchable/search_engine/elasticsearch.rb', line 26

def init_search_engine(*names)
  index_name Rails.application.class.parent_name.underscore
  document_type self.name.downcase

  fields = names.flatten.inject([]) do |result_arr, name|
    if name.is_a? Symbol
      result_arr << name
    elsif name.is_a? Hash
      name.keys.each do |key|
        array = name[key]
        raise(
          BadDataType,
          "searchable_attributes associations can only have Array"
        ) unless array.is_a? Array

        result = array.inject([]) do |array, element|
          raise(
            BadDataType,
            "searchable_attributes associations
            attributes can only have Symbol"
          ) unless array.is_a? Array

          array << key.to_s + "." + element.to_s
        end

        result_arr << result
      end
    else
      raise(
        BadDataType,
        "searchable_attributes can only be either a Symbol or an Hash"
      )
    end

    result_arr.flatten
  end

  define_singleton_method(:call_search) do |term|
    __elasticsearch__.search(
      { query:
        { multi_match:
          { query: term, fields: fields}
        },
        size: 10000,
      }
    )
  end

  as_indexed_hash = names.flatten.inject({}) do |result_hash, name|
    if name.is_a? Hash
      name.keys.each do |key|
        array = name[key]
        raise(
          BadDataType,
          "searchable_attributes associations can only have Array"
        ) unless array.is_a? Array

        result_hash[key] = { only: array }
      end
    end

    result_hash
  end

  define_method(:as_indexed_json) do |options|
    self.as_json(only: names.flatten, include: as_indexed_hash)
  end
end

#reindex_search_engine!Object



100
101
102
103
104
105
106
# File 'lib/switch_searchable/search_engine/elasticsearch.rb', line 100

def reindex_search_engine!
  puts "Creating index..."
  __elasticsearch__.create_index! force: true
  __elasticsearch__.refresh_index!
  puts "Importing data..."
  import
end

#search(term) ⇒ Object



95
96
97
98
# File 'lib/switch_searchable/search_engine/elasticsearch.rb', line 95

def search(term)
  connection
  call_search(term).records
end