search_index_backend.rb 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class SearchIndexBackend
  3. SUPPORTED_ES_VERSION_MINIMUM = '7.8'.freeze
  4. SUPPORTED_ES_VERSION_LESS_THAN = '9'.freeze
  5. =begin
  6. info about used search index machine
  7. SearchIndexBackend.info
  8. =end
  9. def self.info
  10. url = Setting.get('es_url').to_s
  11. return if url.blank?
  12. response = make_request(url)
  13. if response.success?
  14. installed_version = response.data.dig('version', 'number')
  15. raise "Unable to get elasticsearch version from response: #{response.inspect}" if installed_version.blank?
  16. installed_version_parsed = Gem::Version.new(installed_version)
  17. if (installed_version_parsed >= Gem::Version.new(SUPPORTED_ES_VERSION_LESS_THAN)) ||
  18. (installed_version_parsed < Gem::Version.new(SUPPORTED_ES_VERSION_MINIMUM))
  19. raise "Version #{installed_version} of configured elasticsearch is not supported."
  20. end
  21. return response.data
  22. end
  23. raise humanized_error(
  24. verb: 'GET',
  25. url: url,
  26. response: response,
  27. )
  28. end
  29. =begin
  30. update processors
  31. SearchIndexBackend.processors(
  32. _ingest/pipeline/attachment: {
  33. description: 'Extract attachment information from arrays',
  34. processors: [
  35. {
  36. foreach: {
  37. field: 'ticket.articles.attachments',
  38. processor: {
  39. attachment: {
  40. target_field: '_ingest._value.attachment',
  41. field: '_ingest._value.data'
  42. }
  43. }
  44. }
  45. }
  46. ]
  47. }
  48. )
  49. =end
  50. def self.processors(data)
  51. data.each do |key, items|
  52. url = "#{Setting.get('es_url')}/#{key}"
  53. items.each do |item|
  54. if item[:action] == 'delete'
  55. response = make_request(url, method: :delete)
  56. next if response.success?
  57. next if response.code.to_s == '404'
  58. raise humanized_error(
  59. verb: 'DELETE',
  60. url: url,
  61. response: response,
  62. )
  63. end
  64. item.delete(:action)
  65. make_request_and_validate(url, data: item, method: :put)
  66. end
  67. end
  68. true
  69. end
  70. =begin
  71. create/update/delete index
  72. SearchIndexBackend.index(
  73. :action => 'create', # create/update/delete
  74. :name => 'Ticket',
  75. :data => {
  76. :mappings => {
  77. :Ticket => {
  78. :properties => {
  79. :articles => {
  80. :type => 'nested',
  81. :properties => {
  82. 'attachment' => { :type => 'attachment' }
  83. }
  84. }
  85. }
  86. }
  87. }
  88. }
  89. )
  90. SearchIndexBackend.index(
  91. :action => 'delete', # create/update/delete
  92. :name => 'Ticket',
  93. )
  94. =end
  95. def self.index(data)
  96. url = build_url(type: data[:name], with_pipeline: false, with_document_type: false)
  97. return if url.blank?
  98. if data[:action] && data[:action] == 'delete'
  99. return if !SearchIndexBackend.index_exists?(data[:name])
  100. return SearchIndexBackend.remove(data[:name])
  101. end
  102. make_request_and_validate(url, data: data[:data], method: :put)
  103. end
  104. =begin
  105. add new object to search index
  106. SearchIndexBackend.add('Ticket', some_data_object)
  107. =end
  108. def self.add(type, data)
  109. url = build_url(type: type, object_id: data['id'])
  110. return if url.blank?
  111. make_request_and_validate(url, data: data, method: :post)
  112. end
  113. =begin
  114. get object of search index by id
  115. SearchIndexBackend.get('Ticket', 123)
  116. =end
  117. def self.get(type, data)
  118. url = build_url(type: type, object_id: data, with_pipeline: false)
  119. return if url.blank?
  120. make_request(url, method: :get).try(:data)
  121. end
  122. =begin
  123. Check if an index exists.
  124. SearchIndexBackend.index_exists?('Ticket')
  125. =end
  126. def self.index_exists?(type)
  127. url = build_url(type: type, with_pipeline: false, with_document_type: false)
  128. return if url.blank?
  129. response = make_request(url)
  130. return true if response.success?
  131. return true if response.code.to_s != '404'
  132. false
  133. end
  134. =begin
  135. This function updates specifc attributes of an index based on a query.
  136. It should get used in batches to prevent performance issues on entities which have millions of objects in it.
  137. data = {
  138. organization: {
  139. name: "Zammad Foundation"
  140. }
  141. }
  142. where = {
  143. term: {
  144. organization_id: 1
  145. }
  146. }
  147. SearchIndexBackend.update_by_query('Ticket', data, where)
  148. =end
  149. def self.update_by_query(type, data, where)
  150. return if data.blank?
  151. return if where.blank?
  152. url_params = {
  153. conflicts: 'proceed',
  154. slices: 'auto',
  155. max_docs: 1_000,
  156. }
  157. url = build_url(type: type, action: '_update_by_query', with_pipeline: false, with_document_type: false, url_params: url_params)
  158. return if url.blank?
  159. script_list = []
  160. data.each_key do |key|
  161. script_list.push("ctx._source.#{key}=params.#{key}")
  162. end
  163. data = {
  164. script: {
  165. lang: 'painless',
  166. source: script_list.join(';'),
  167. params: data,
  168. },
  169. query: where,
  170. sort: {
  171. id: 'desc',
  172. },
  173. }
  174. response = make_request(url, data: data, method: :post, read_timeout: 10.minutes)
  175. if !response.success?
  176. Rails.logger.error humanized_error(
  177. verb: 'GET',
  178. url: url,
  179. payload: data,
  180. response: response,
  181. )
  182. return []
  183. end
  184. response.data
  185. end
  186. =begin
  187. remove whole data from index
  188. SearchIndexBackend.remove('Ticket', 123)
  189. SearchIndexBackend.remove('Ticket')
  190. =end
  191. def self.remove(type, o_id = nil)
  192. url = if o_id
  193. build_url(type: type, object_id: o_id, with_pipeline: false, with_document_type: true)
  194. else
  195. build_url(type: type, object_id: o_id, with_pipeline: false, with_document_type: false)
  196. end
  197. return if url.blank?
  198. response = make_request(url, method: :delete)
  199. return true if response.success?
  200. return true if response.code.to_s == '400'
  201. humanized_error = humanized_error(
  202. verb: 'DELETE',
  203. url: url,
  204. response: response,
  205. )
  206. Rails.logger.warn "Can't delete index: #{humanized_error}"
  207. false
  208. end
  209. =begin
  210. @param query [String] search query
  211. @param index [String, Array<String>] indexes to search in (see search_by_index)
  212. @param options [Hash] search options (see build_query)
  213. @return search result
  214. @example Sample queries
  215. result = SearchIndexBackend.search('search query', ['User', 'Organization'], limit: limit)
  216. - result = SearchIndexBackend.search('search query', 'User', limit: limit)
  217. result = SearchIndexBackend.search('search query', 'User', limit: limit, sort_by: ['updated_at'], order_by: ['desc'])
  218. result = SearchIndexBackend.search('search query', 'User', limit: limit, sort_by: ['active', updated_at'], order_by: ['desc', 'desc'])
  219. result = [
  220. {
  221. :id => 123,
  222. :type => 'User',
  223. },
  224. {
  225. :id => 125,
  226. :type => 'User',
  227. },
  228. {
  229. :id => 15,
  230. :type => 'Organization',
  231. }
  232. ]
  233. =end
  234. def self.search(query, index, options = {})
  235. if !index.is_a? Array
  236. return search_by_index(query, index, options)
  237. end
  238. index
  239. .filter_map { |local_index| search_by_index(query, local_index, options) }
  240. .flatten(1)
  241. end
  242. =begin
  243. @param query [String] search query
  244. @param index [String] index name
  245. @param options [Hash] search options (see build_query)
  246. @return search result
  247. =end
  248. def self.search_by_index(query, index, options = {})
  249. return [] if query.blank?
  250. url = build_url(type: index, action: '_search', with_pipeline: false, with_document_type: false)
  251. return [] if url.blank?
  252. # real search condition
  253. condition = {
  254. 'query_string' => {
  255. 'query' => append_wildcard_to_simple_query(query),
  256. 'time_zone' => Setting.get('timezone_default'),
  257. 'default_operator' => 'AND',
  258. 'analyze_wildcard' => true,
  259. }
  260. }
  261. if (fields = options.dig(:query_fields_by_indexes, index.to_sym))
  262. condition['query_string']['fields'] = fields
  263. end
  264. query_data = build_query(index, condition, options)
  265. if (fields = options.dig(:highlight_fields_by_indexes, index.to_sym))
  266. fields_for_highlight = fields.index_with { |_elem| {} }
  267. query_data[:highlight] = { fields: fields_for_highlight }
  268. end
  269. response = make_request(url, data: query_data, method: :post)
  270. if !response.success?
  271. Rails.logger.error humanized_error(
  272. verb: 'GET',
  273. url: url,
  274. payload: query_data,
  275. response: response,
  276. )
  277. return []
  278. end
  279. data = response.data&.dig('hits', 'hits')
  280. return [] if !data
  281. data.map do |item|
  282. Rails.logger.debug { "... #{item['_type']} #{item['_id']}" }
  283. output = {
  284. id: item['_id'],
  285. type: index,
  286. }
  287. if options.dig(:highlight_fields_by_indexes, index.to_sym)
  288. output[:highlight] = item['highlight']
  289. end
  290. output
  291. end
  292. end
  293. def self.search_by_index_sort(index:, sort_by: nil, order_by: nil, fulltext: false)
  294. result = (sort_by || [])
  295. .map(&:to_s)
  296. .each_with_object([])
  297. .with_index do |(elem, memo), idx|
  298. next if elem.blank?
  299. next if order_by&.at(idx).blank?
  300. # for sorting values use .keyword values (no analyzer is used - plain values)
  301. is_keyword = get_mapping_properties_object(Array.wrap(index).first.constantize).dig(:properties, elem, :fields, :keyword, :type) == 'keyword'
  302. if is_keyword
  303. elem += '.keyword'
  304. end
  305. memo.push(
  306. elem => {
  307. order: order_by[idx],
  308. },
  309. )
  310. end
  311. # if we have no fulltext search then the primary default sort is updated at else score
  312. if result.blank? && !fulltext
  313. result.push(
  314. updated_at: {
  315. order: 'desc',
  316. },
  317. )
  318. end
  319. result.push('_score')
  320. result
  321. end
  322. =begin
  323. get count of tickets and tickets which match on selector
  324. result = SearchIndexBackend.selectors(index, selector)
  325. example with a simple search:
  326. result = SearchIndexBackend.selectors('Ticket', { 'category' => { 'operator' => 'is', 'value' => 'aa::ab' } })
  327. result = [
  328. { id: 1, type: 'Ticket' },
  329. { id: 2, type: 'Ticket' },
  330. { id: 3, type: 'Ticket' },
  331. ]
  332. you also can get aggregations
  333. result = SearchIndexBackend.selectors(index, selector, options, aggs_interval)
  334. example for aggregations within one year
  335. aggs_interval = {
  336. from: '2015-01-01',
  337. to: '2015-12-31',
  338. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  339. field: 'created_at',
  340. }
  341. options = {
  342. limit: 123,
  343. current_user: User.find(123),
  344. }
  345. result = SearchIndexBackend.selectors('Ticket', { 'category' => { 'operator' => 'is', 'value' => 'aa::ab' } }, options, aggs_interval)
  346. result = {
  347. hits:{
  348. total:4819,
  349. },
  350. aggregations:{
  351. time_buckets:{
  352. buckets:[
  353. {
  354. key_as_string:"2014-10-01T00:00:00.000Z",
  355. key:1412121600000,
  356. doc_count:420
  357. },
  358. {
  359. key_as_string:"2014-11-01T00:00:00.000Z",
  360. key:1414800000000,
  361. doc_count:561
  362. },
  363. ...
  364. ]
  365. }
  366. }
  367. }
  368. =end
  369. def self.selectors(index, selectors = nil, options = {}, aggs_interval = nil)
  370. raise 'no selectors given' if !selectors
  371. url = build_url(type: index, action: '_search', with_pipeline: false, with_document_type: false)
  372. return if url.blank?
  373. data = selector2query(index, selectors, options, aggs_interval)
  374. response = make_request(url, data: data, method: :post)
  375. with_interval = aggs_interval.present? && aggs_interval[:interval].present?
  376. if !response.success?
  377. # Work around a bug with ES versions <= 8.5.0, where invalid date range conditions caused an error response from the server.
  378. # https://github.com/zammad/zammad/issues/5105, https://github.com/elastic/elasticsearch/issues/88131
  379. # This can probably be removed when the required minimum ES version is >= 8.5.0.
  380. if with_interval && response.code.to_i == 400 && response.body&.include?('illegal_argument_exception')
  381. return fake_empty_es_aggregation_response
  382. end
  383. raise humanized_error(
  384. verb: 'GET',
  385. url: url,
  386. payload: data,
  387. response: response,
  388. )
  389. end
  390. Rails.logger.debug { response.data.to_json }
  391. if !with_interval
  392. object_ids = []
  393. response.data['hits']['hits'].each do |item|
  394. object_ids.push item['_id']
  395. end
  396. # in lower ES 6 versions, we get total count directly, in higher
  397. # versions we need to pick it from total has
  398. count = response.data['hits']['total']
  399. if response.data['hits']['total'].class != Integer
  400. count = response.data['hits']['total']['value']
  401. end
  402. return {
  403. count: count,
  404. object_ids: object_ids,
  405. }
  406. end
  407. response.data
  408. end
  409. def self.selector2query(index, selector, options, aggs_interval)
  410. Selector::SearchIndex.new(selector: selector, options: options.merge(aggs_interval: aggs_interval), target_class: index.constantize).get
  411. end
  412. =begin
  413. return true if backend is configured
  414. result = SearchIndexBackend.enabled?
  415. =end
  416. def self.enabled?
  417. return false if Setting.get('es_url').blank?
  418. true
  419. end
  420. def self.build_index_name(index = nil)
  421. local_index = "#{Setting.get('es_index')}_#{Rails.env}"
  422. return local_index if index.blank?
  423. "#{local_index}_#{index.underscore.tr('/', '_')}"
  424. end
  425. =begin
  426. generate url for index or document access (only for internal use)
  427. # url to access single document in index (in case with_pipeline or not)
  428. url = SearchIndexBackend.build_url(type: 'User', object_id: 123, with_pipeline: true)
  429. # url to access whole index
  430. url = SearchIndexBackend.build_url(type: 'User')
  431. # url to access document definition in index (only es6 and higher)
  432. url = SearchIndexBackend.build_url(type: 'User', with_pipeline: false, with_document_type: true)
  433. # base url
  434. url = SearchIndexBackend.build_url
  435. =end
  436. def self.build_url(type: nil, action: nil, object_id: nil, with_pipeline: true, with_document_type: true, url_params: {})
  437. return if !SearchIndexBackend.enabled?
  438. # set index
  439. index = build_index_name(type)
  440. # add pipeline if needed
  441. if index && with_pipeline == true
  442. url_pipline = Setting.get('es_pipeline')
  443. if url_pipline.present?
  444. url_params['pipeline'] = url_pipline
  445. end
  446. end
  447. # prepare url params
  448. params_string = ''
  449. if url_params.present?
  450. params_string = "?#{URI.encode_www_form(url_params)}"
  451. end
  452. url = Setting.get('es_url')
  453. return "#{url}#{params_string}" if index.blank?
  454. # add type information
  455. url = "#{url}/#{index}"
  456. # add document type
  457. if with_document_type
  458. url = "#{url}/_doc"
  459. end
  460. # add action
  461. if action
  462. url = "#{url}/#{action}"
  463. end
  464. # add object id
  465. if object_id.present?
  466. url = "#{url}/#{object_id}"
  467. end
  468. "#{url}#{params_string}"
  469. end
  470. def self.humanized_error(verb:, url:, response:, payload: nil)
  471. prefix = "Unable to process #{verb} request to elasticsearch URL '#{url}'."
  472. suffix = "\n\nResponse:\n#{response.inspect}\n\n"
  473. if payload.respond_to?(:to_json)
  474. suffix += "Payload:\n#{payload.to_json}"
  475. suffix += "\n\nPayload size: #{payload.to_json.bytesize / 1024 / 1024}M"
  476. else
  477. suffix += "Payload:\n#{payload.inspect}"
  478. end
  479. message = if response&.error&.match?('Connection refused') # rubocop:disable Zammad/DetectTranslatableString
  480. __("Elasticsearch is not reachable. It's possible that it's not running. Please check whether it is installed.")
  481. elsif url.end_with?('pipeline/zammad-attachment', 'pipeline=zammad-attachment') && response.code == 400
  482. __('The installed attachment plugin could not handle the request payload. Ensure that the correct attachment plugin is installed (ingest-attachment).')
  483. else
  484. __('Check the response and payload for detailed information:')
  485. end
  486. result = "#{prefix} #{message}#{suffix}"
  487. Rails.logger.error result.first(40_000)
  488. result
  489. end
  490. # add * on simple query like "somephrase23"
  491. def self.append_wildcard_to_simple_query(query)
  492. query = query.strip
  493. query += '*' if query.exclude?(':')
  494. query
  495. end
  496. =begin
  497. @param condition [Hash] search condition
  498. @param options [Hash] search options
  499. @option options [Integer] :from
  500. @option options [Integer] :limit
  501. @option options [Hash] :query_extension applied to ElasticSearch query
  502. @option options [Array<String>] :order_by ordering directions, desc or asc
  503. @option options [Array<String>] :sort_by fields to sort by
  504. @option options [Array<String>] :fulltext If no sorting is defined the current fallback is the sorting by updated_at. But for fulltext searches it makes more sense to search by _score as default. This parameter allows to change to the fallback to _score.
  505. =end
  506. DEFAULT_QUERY_OPTIONS = {
  507. from: 0,
  508. limit: 10
  509. }.freeze
  510. def self.build_query(index, condition, options = {})
  511. options = DEFAULT_QUERY_OPTIONS.merge(options.deep_symbolize_keys)
  512. data = {
  513. from: options[:from],
  514. size: options[:limit],
  515. sort: search_by_index_sort(index: index, sort_by: options[:sort_by], order_by: options[:order_by], fulltext: options[:fulltext]),
  516. query: {
  517. bool: {
  518. must: []
  519. }
  520. }
  521. }
  522. if (extension = options[:query_extension])
  523. data[:query].deep_merge! extension.deep_dup
  524. end
  525. data[:query][:bool][:must].push condition
  526. if options[:ids].present?
  527. data[:query][:bool][:must].push({ ids: { values: options[:ids] } })
  528. end
  529. data
  530. end
  531. =begin
  532. refreshes all indexes to make previous request data visible in future requests
  533. SearchIndexBackend.refresh
  534. =end
  535. def self.refresh
  536. return if !enabled?
  537. url = "#{Setting.get('es_url')}/_all/_refresh"
  538. make_request_and_validate(url, method: :post)
  539. end
  540. =begin
  541. helper method for making HTTP calls
  542. @param url [String] url
  543. @option params [Hash] :data is a payload hash
  544. @option params [Symbol] :method is a HTTP method
  545. @option params [Integer] :open_timeout is HTTP request open timeout
  546. @option params [Integer] :read_timeout is HTTP request read timeout
  547. @return UserAgent response
  548. =end
  549. def self.make_request(url, data: {}, method: :get, open_timeout: 8, read_timeout: 180)
  550. Rails.logger.debug { "# curl -X #{method} \"#{url}\" " }
  551. Rails.logger.debug { "-d '#{data.to_json}'" } if data.present?
  552. options = {
  553. json: true,
  554. open_timeout: open_timeout,
  555. read_timeout: read_timeout,
  556. total_timeout: (open_timeout + read_timeout + 60),
  557. open_socket_tries: 3,
  558. user: Setting.get('es_user'),
  559. password: Setting.get('es_password'),
  560. verify_ssl: Setting.get('es_ssl_verify'),
  561. }
  562. response = UserAgent.send(method, url, data, options)
  563. Rails.logger.debug { "# #{response.code}" }
  564. response
  565. end
  566. =begin
  567. helper method for making HTTP calls and raising error if response was not success
  568. @param url [String] url
  569. @option args [Hash] see {make_request}
  570. @return [Boolean] always returns true. Raises error if something went wrong.
  571. =end
  572. def self.make_request_and_validate(url, **args)
  573. response = make_request(url, **args)
  574. return true if response.success?
  575. raise humanized_error(
  576. verb: args[:method],
  577. url: url,
  578. payload: args[:data],
  579. response: response
  580. )
  581. end
  582. =begin
  583. This function will return a index mapping based on the
  584. attributes of the database table of the existing object.
  585. mapping = SearchIndexBackend.get_mapping_properties_object(Ticket)
  586. Returns:
  587. mapping = {
  588. User: {
  589. properties: {
  590. firstname: {
  591. type: 'keyword',
  592. },
  593. }
  594. }
  595. }
  596. =end
  597. def self.get_mapping_properties_object(object)
  598. result = {
  599. properties: {}
  600. }
  601. store_columns = %w[preferences data]
  602. # for elasticsearch 6.x and later
  603. string_type = 'text'
  604. string_raw = { type: 'keyword', ignore_above: 5012 }
  605. boolean_raw = { type: 'boolean' }
  606. object.columns_hash.each do |key, value|
  607. if value.type == :string && value.limit && value.limit <= 5000 && store_columns.exclude?(key)
  608. result[:properties][key] = {
  609. type: string_type,
  610. fields: {
  611. keyword: string_raw,
  612. }
  613. }
  614. elsif value.type == :integer
  615. result[:properties][key] = {
  616. type: 'integer',
  617. }
  618. elsif value.type == :datetime || value.type == :date
  619. result[:properties][key] = {
  620. type: 'date',
  621. }
  622. elsif value.type == :boolean
  623. result[:properties][key] = {
  624. type: 'boolean',
  625. fields: {
  626. keyword: boolean_raw,
  627. }
  628. }
  629. elsif value.type == :binary
  630. result[:properties][key] = {
  631. type: 'binary',
  632. }
  633. elsif value.type == :bigint
  634. result[:properties][key] = {
  635. type: 'long',
  636. }
  637. elsif value.type == :decimal
  638. result[:properties][key] = {
  639. type: 'float',
  640. }
  641. end
  642. end
  643. case object.name
  644. when 'Ticket'
  645. result[:properties][:article] = {
  646. type: 'nested',
  647. include_in_parent: true,
  648. }
  649. end
  650. result
  651. end
  652. # get es version
  653. def self.version
  654. @version ||= SearchIndexBackend.info&.dig('version', 'number')
  655. end
  656. def self.configured?
  657. Setting.get('es_url').present?
  658. end
  659. def self.model_indexable?(model_name)
  660. Models.indexable.any? { |m| m.name == model_name }
  661. end
  662. def self.default_model_settings
  663. {
  664. 'index.mapping.total_fields.limit' => 2000,
  665. }
  666. end
  667. def self.model_settings(model)
  668. settings = Setting.get('es_model_settings')[model.name] || {}
  669. default_model_settings.merge(settings)
  670. end
  671. def self.all_settings
  672. Models.indexable.each_with_object({}).to_h { |m| [m.name, model_settings(m)] }
  673. end
  674. def self.set_setting(model_name, key, value)
  675. raise "It is not possible to configure settings for the non-indexable model '#{model_name}'." if !model_indexable?(model_name)
  676. raise __("The required parameter 'key' is missing.") if key.blank?
  677. raise __("The required parameter 'value' is missing.") if value.blank?
  678. config = Setting.get('es_model_settings')
  679. config[model_name] ||= {}
  680. config[model_name][key] = value
  681. Setting.set('es_model_settings', config)
  682. end
  683. def self.unset_setting(model_name, key)
  684. raise "It is not possible to configure settings for the non-indexable model '#{model_name}'." if !model_indexable?(model_name)
  685. raise __("The required parameter 'key' is missing.") if key.blank?
  686. config = Setting.get('es_model_settings')
  687. config[model_name] ||= {}
  688. config[model_name].delete(key)
  689. Setting.set('es_model_settings', config)
  690. end
  691. def self.create_index(models = Models.indexable)
  692. models.each do |local_object|
  693. SearchIndexBackend.index(
  694. action: 'create',
  695. name: local_object.name,
  696. data: {
  697. mappings: SearchIndexBackend.get_mapping_properties_object(local_object),
  698. settings: model_settings(local_object),
  699. }
  700. )
  701. end
  702. end
  703. def self.drop_index(models = Models.indexable)
  704. models.each do |local_object|
  705. SearchIndexBackend.index(
  706. action: 'delete',
  707. name: local_object.name,
  708. )
  709. end
  710. end
  711. def self.create_object_index(object)
  712. models = Models.indexable.select { |c| c.to_s == object }
  713. create_index(models)
  714. end
  715. def self.drop_object_index(object)
  716. models = Models.indexable.select { |c| c.to_s == object }
  717. drop_index(models)
  718. end
  719. def self.pipeline(create: false)
  720. pipeline = Setting.get('es_pipeline')
  721. if create && pipeline.blank?
  722. pipeline = "zammad#{SecureRandom.uuid}"
  723. Setting.set('es_pipeline', pipeline)
  724. end
  725. pipeline
  726. end
  727. def self.pipeline_settings
  728. {
  729. ignore_failure: true,
  730. ignore_missing: true,
  731. }
  732. end
  733. def self.create_pipeline
  734. SearchIndexBackend.processors(
  735. "_ingest/pipeline/#{pipeline(create: true)}": [
  736. {
  737. action: 'delete',
  738. },
  739. {
  740. action: 'create',
  741. description: __('Extract zammad-attachment information from arrays'),
  742. processors: [
  743. {
  744. foreach: {
  745. field: 'article',
  746. processor: {
  747. foreach: {
  748. field: '_ingest._value.attachment',
  749. processor: {
  750. attachment: {
  751. target_field: '_ingest._value',
  752. field: '_ingest._value._content',
  753. }.merge(pipeline_settings),
  754. }
  755. }.merge(pipeline_settings),
  756. }
  757. }.merge(pipeline_settings),
  758. },
  759. {
  760. foreach: {
  761. field: 'attachment',
  762. processor: {
  763. attachment: {
  764. target_field: '_ingest._value',
  765. field: '_ingest._value._content',
  766. }.merge(pipeline_settings),
  767. }
  768. }.merge(pipeline_settings),
  769. }
  770. ]
  771. }
  772. ]
  773. )
  774. end
  775. def self.drop_pipeline
  776. return if pipeline.blank?
  777. SearchIndexBackend.processors(
  778. "_ingest/pipeline/#{pipeline}": [
  779. {
  780. action: 'delete',
  781. },
  782. ]
  783. )
  784. end
  785. # Simulate an empty response from ES.
  786. def self.fake_empty_es_aggregation_response
  787. {
  788. 'hits' => { 'total' => { 'value' => 0, 'relation' => 'eq' }, 'max_score' => nil, 'hits' => [] },
  789. 'aggregations' => { 'time_buckets' => { 'buckets' => [] } }
  790. }
  791. end
  792. end