Skip to content

Instantly share code, notes, and snippets.

@bsa7
Created December 7, 2018 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsa7/4c14bfff3066b52b9568d32b1a97d05e to your computer and use it in GitHub Desktop.
Save bsa7/4c14bfff3066b52b9568d32b1a97d05e to your computer and use it in GitHub Desktop.
interface for elastic
# frozen_string_literal: true
require 'elasticsearch'
connection_params = {
log: false,
}
connection_params[:user] = ENV['ELASTICSEARCH_USERNAME'] || 'elastic'
connection_params[:password] = ENV['ELASTICSEARCH_USERPASSWORD'] || 'elastic'
connection_params[:host] = ENV['ELASTICSEARCH_HOST'] || 'localhost'
connection_params[:port] = ENV['ELASTICSEARCH_PORT'] || '9200'
ElasticClient ||= Elasticsearch::Client.new(hosts: connection_params)
module Api
module V2
module ElasticsearchHelper
# Массовое выполнение
def self.bulk(params)
ElasticClient.bulk(params)
end
def self.client
ElasticClient
end
# Создаёт индекс с заданными параметрами
def self.create_index(params)
ElasticClient.indices.create(params) unless index_exists?(index_name: params[:index])
end
# Создаёт индекс с заданными параметрами, удаляя существующий, если такой есть
def self.create_index!(params)
delete_index(index_name: params[:index]) if index_exists?(index_name: params[:index])
create_index(params)
end
# Удаляет индекс
def self.delete_index(index_name:)
ElasticClient.indices.delete(index: index_name)
end
# Индексация с возможностью асинхронного вызова (Elastic.async.document_index...)
def self.document_index(index:, type:, body:, id: nil)
updated = false
if id
document_exists = ElasticClient.exists({
id: id,
index: index,
type: type,
})
if document_exists
updated = true
ElasticClient.update({
id: id,
index: index,
type: type,
body: { doc: body },
})
end
end
return if updated
id ||= create_random_id()
ElasticClient.create({
id: id,
index: index,
refresh: true,
type: type,
body: body,
})
end
def self.get(id:, index:, type:)
ElasticClient.get({
id: id,
index: index,
type: type,
})
end
def self.delete(params)
ElasticClient.delete(params)
end
def self.delete_by_query(params)
ElasticClient.delete_by_query(params)
end
# Определяет, существует ли индекс
def self.index_exists?(index_name:)
ElasticClient.indices.get_settings.has_key?(index_name.to_s)
end
# Индексирует данные в индексе elasticsearch
def self.index(params)
ElasticClient.index(params)
end
# Обновляет данные в индексе elasticsearch
def self.update(params)
ElasticClient.update(params)
end
# Выполняет поиск в заданном индексе
# Выполняет роль порта к клиенту elastcisearch, не требуя инициализации клиента
def self.search(params)
ElasticClient.search(params)
end
def self.values_exists?(hash, attribute_names)
result = true
(attribute_names || []).each do |attribute_name|
if hash[attribute_name.to_s].blank?
result = false
break
end
end
result
end
def self.update_attributes(index:, type:, id:, params: {})
ElasticClient.bulk({
body: [{
update: {
_index: index,
_type: type,
_id: id,
data: {
doc: params,
}
}
}]
})
end
def self.create_random_id
Digest::SHA256.hexdigest(Time.zone.now.strftime('%Y-%m-%d %H:%M:%S:%N'))[0..20]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment