search.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class KnowledgeBase
  3. module Search
  4. extend ActiveSupport::Concern
  5. class_methods do
  6. def search(params)
  7. current_user = params[:current_user]
  8. # enable search only for agents and admins
  9. return [] if !search_preferences(current_user)
  10. sql_helper = ::SqlHelper.new(object: self)
  11. options = {
  12. limit: params[:limit] || 10,
  13. from: params[:offset] || 0,
  14. sort_by: sql_helper.get_sort_by(params, 'updated_at'),
  15. order_by: sql_helper.get_order_by(params, 'desc'),
  16. user: current_user
  17. }
  18. kb_locales = KnowledgeBase.active.map { |elem| KnowledgeBase::Locale.preferred(current_user, elem) }
  19. # try search index backend
  20. if SearchIndexBackend.enabled?
  21. search_es(params[:query], kb_locales, options)
  22. else
  23. # fallback do sql query
  24. search_sql(params[:query], kb_locales, options)
  25. end
  26. end
  27. def search_es(query, kb_locales, options)
  28. options[:query_extension] = { bool: { filter: { terms: { kb_locale_id: kb_locales.map(&:id) } } } }
  29. es_response = SearchIndexBackend.search(query, name, options)
  30. es_response = search_es_filter(es_response, query, kb_locales, options) if defined? :search_es_filter
  31. es_response.filter_map { |item| lookup(id: item[:id]) }
  32. end
  33. def search_sql(query, kb_locales, options)
  34. table_name = arel_table.name
  35. sql_helper = ::SqlHelper.new(object: self)
  36. order_sql = sql_helper.get_order(options[:sort_by], options[:order_by], "#{table_name}.updated_at ASC")
  37. # - strip out * we already search for *query* -
  38. query = query.delete '*'
  39. search_fallback("%#{query}%", options: options)
  40. .where(kb_locale: kb_locales)
  41. .order(Arel.sql(order_sql))
  42. .offset(options[:from])
  43. .limit(options[:limit])
  44. .to_a
  45. end
  46. end
  47. end
  48. end