2021-06-01 12:20:20 +00:00
|
|
|
# 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)
|
|
|
|
|
2020-10-30 07:59:32 +00:00
|
|
|
sql_helper = ::SqlHelper.new(object: self)
|
|
|
|
|
2019-06-04 03:40:48 +00:00
|
|
|
options = {
|
|
|
|
limit: params[:limit] || 10,
|
|
|
|
from: params[:offset] || 0,
|
2020-10-30 07:59:32 +00:00
|
|
|
sort_by: sql_helper.get_sort_by(params, 'updated_at'),
|
|
|
|
order_by: sql_helper.get_order_by(params, 'desc'),
|
2020-08-05 13:48:41 +00:00
|
|
|
user: current_user
|
2019-06-04 03:40:48 +00:00
|
|
|
}
|
|
|
|
|
2020-09-23 14:10:50 +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?
|
2020-09-23 14:10:50 +00:00
|
|
|
search_es(params[:query], kb_locales, options)
|
2019-06-04 03:40:48 +00:00
|
|
|
else
|
|
|
|
# fallback do sql query
|
2020-09-23 14:10:50 +00:00
|
|
|
search_sql(params[:query], kb_locales, options)
|
2019-06-04 03:40:48 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-09-23 14:10:50 +00:00
|
|
|
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
|
|
|
|
2020-08-05 13:48:41 +00:00
|
|
|
es_response = SearchIndexBackend.search(query, name, options)
|
2020-09-23 14:10:50 +00:00
|
|
|
es_response = search_es_filter(es_response, query, kb_locales, options) if defined? :search_es_filter
|
2020-08-05 13:48:41 +00:00
|
|
|
|
|
|
|
es_response.map { |item| lookup(id: item[:id]) }.compact
|
2019-06-04 03:40:48 +00:00
|
|
|
end
|
|
|
|
|
2020-09-23 14:10:50 +00:00
|
|
|
def search_sql(query, kb_locales, options)
|
2020-10-30 07:59:32 +00:00
|
|
|
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! '*'
|
|
|
|
|
2020-08-05 13:48:41 +00:00
|
|
|
search_fallback("%#{query}%", options: options)
|
2020-09-23 14:10:50 +00:00
|
|
|
.where(kb_locale: kb_locales)
|
2020-08-05 13:48:41 +00:00
|
|
|
.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
|