Class: Rails::Contact::Search::Backends::Elasticsearch

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/contact/search/backends/elasticsearch.rb

Constant Summary collapse

INDEX =
"rails_contact_contacts".freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client: nil) ⇒ Elasticsearch

Returns a new instance of Elasticsearch.



22
23
24
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 22

def initialize(client: nil)
  @client = client || self.class.default_client
end

Class Method Details

.clear_default_client!Object



17
18
19
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 17

def clear_default_client!
  @default_client = nil
end

.default_clientObject



9
10
11
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 9

def default_client
  @default_client ||= ::Elasticsearch::Client.new(url: Rails::Contact.configuration.elasticsearch_url)
end

.default_client=(client) ⇒ Object



13
14
15
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 13

def default_client=(client)
  @default_client = client
end

Instance Method Details

#create_index!Object



48
49
50
51
52
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 48

def create_index!
  return if @client.indices.exists?(index: INDEX)

  @client.indices.create(index: INDEX, body: index_mapping)
end

#remove(contact_id) ⇒ Object



42
43
44
45
46
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 42

def remove(contact_id)
  @client.delete(index: INDEX, id: contact_id)
rescue StandardError
  nil
end

#search(query, filters, page:, per_page:) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 26

def search(query, filters, page:, per_page:)
  response = @client.search(index: INDEX, body: search_body(query, filters, page: page, per_page: per_page))
  hits = response.fetch("hits", {})
  ids = hits.fetch("hits", []).map { |doc| doc["_id"] }
  total_count = extract_total_hits(hits["total"])
  records_by_id = Contact.where(id: ids).index_by { |record| record.id.to_s }
  records = ids.filter_map { |id| records_by_id[id.to_s] }
  Search::Result.new(records: records, total_count: total_count, page: page, per_page: per_page)
rescue StandardError
  Search::Backends::Database.new.search(query, filters, page: page, per_page: per_page)
end

#upsert(contact) ⇒ Object



38
39
40
# File 'lib/rails/contact/search/backends/elasticsearch.rb', line 38

def upsert(contact)
  @client.index(index: INDEX, id: contact.id, body: document_for(contact))
end