trabajo-afectivo/app/models/knowledge_base/search.rb

61 lines
2 KiB
Ruby
Raw Normal View History

# Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
2019-06-04 03:40:48 +00:00
class KnowledgeBase
module Search
extend ActiveSupport::Concern
class_methods do
def search(params)
current_user = params[:current_user]
# enable search only for agents and admins
return [] if !search_preferences(current_user)
sql_helper = ::SqlHelper.new(object: self)
2019-06-04 03:40:48 +00:00
options = {
limit: params[:limit] || 10,
from: params[:offset] || 0,
sort_by: sql_helper.get_sort_by(params, 'updated_at'),
order_by: sql_helper.get_order_by(params, 'desc'),
user: current_user
2019-06-04 03:40:48 +00:00
}
kb_locales = KnowledgeBase.active.map { |elem| KnowledgeBase::Locale.preferred(current_user, elem) }
2019-06-04 03:40:48 +00:00
# try search index backend
if SearchIndexBackend.enabled?
search_es(params[:query], kb_locales, options)
2019-06-04 03:40:48 +00:00
else
# fallback do sql query
search_sql(params[:query], kb_locales, options)
2019-06-04 03:40:48 +00:00
end
end
def search_es(query, kb_locales, options)
options[:query_extension] = { bool: { filter: { terms: { kb_locale_id: kb_locales.map(&:id) } } } }
2019-06-04 03:40:48 +00:00
es_response = SearchIndexBackend.search(query, name, options)
es_response = search_es_filter(es_response, query, kb_locales, options) if defined? :search_es_filter
2021-06-24 07:05:39 +00:00
es_response.filter_map { |item| lookup(id: item[:id]) }
2019-06-04 03:40:48 +00:00
end
def search_sql(query, kb_locales, options)
table_name = arel_table.name
sql_helper = ::SqlHelper.new(object: self)
order_sql = sql_helper.get_order(options[:sort_by], options[:order_by], "#{table_name}.updated_at ASC")
2019-06-04 03:40:48 +00:00
# - stip out * we already search for *query* -
query.delete! '*'
search_fallback("%#{query}%", options: options)
.where(kb_locale: kb_locales)
.order(Arel.sql(order_sql))
2019-06-04 03:40:48 +00:00
.offset(options[:from])
.limit(options[:limit])
.to_a
end
end
end
end