search_index_backend.rb 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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 = response.data['hits']['hits'].pluck('_id')
  393. # in lower ES 6 versions, we get total count directly, in higher
  394. # versions we need to pick it from total has
  395. count = response.data['hits']['total']
  396. if response.data['hits']['total'].class != Integer
  397. count = response.data['hits']['total']['value']
  398. end
  399. return {
  400. count: count,
  401. object_ids: object_ids,
  402. }
  403. end
  404. response.data
  405. end
  406. def self.selector2query(index, selector, options, aggs_interval)
  407. Selector::SearchIndex.new(selector: selector, options: options.merge(aggs_interval: aggs_interval), target_class: index.constantize).get
  408. end
  409. =begin
  410. return true if backend is configured
  411. result = SearchIndexBackend.enabled?
  412. =end
  413. def self.enabled?
  414. return false if Setting.get('es_url').blank?
  415. true
  416. end
  417. def self.build_index_name(index = nil)
  418. local_index = "#{Setting.get('es_index')}_#{Rails.env}"
  419. return local_index if index.blank?
  420. "#{local_index}_#{index.underscore.tr('/', '_')}"
  421. end
  422. =begin
  423. generate url for index or document access (only for internal use)
  424. # url to access single document in index (in case with_pipeline or not)
  425. url = SearchIndexBackend.build_url(type: 'User', object_id: 123, with_pipeline: true)
  426. # url to access whole index
  427. url = SearchIndexBackend.build_url(type: 'User')
  428. # url to access document definition in index (only es6 and higher)
  429. url = SearchIndexBackend.build_url(type: 'User', with_pipeline: false, with_document_type: true)
  430. # base url
  431. url = SearchIndexBackend.build_url
  432. =end
  433. def self.build_url(type: nil, action: nil, object_id: nil, with_pipeline: true, with_document_type: true, url_params: {})
  434. return if !SearchIndexBackend.enabled?
  435. # set index
  436. index = build_index_name(type)
  437. # add pipeline if needed
  438. if index && with_pipeline == true
  439. url_pipline = Setting.get('es_pipeline')
  440. if url_pipline.present?
  441. url_params['pipeline'] = url_pipline
  442. end
  443. end
  444. # prepare url params
  445. params_string = ''
  446. if url_params.present?
  447. params_string = "?#{URI.encode_www_form(url_params)}"
  448. end
  449. url = Setting.get('es_url')
  450. return "#{url}#{params_string}" if index.blank?
  451. # add type information
  452. url = "#{url}/#{index}"
  453. # add document type
  454. if with_document_type
  455. url = "#{url}/_doc"
  456. end
  457. # add action
  458. if action
  459. url = "#{url}/#{action}"
  460. end
  461. # add object id
  462. if object_id.present?
  463. url = "#{url}/#{object_id}"
  464. end
  465. "#{url}#{params_string}"
  466. end
  467. def self.humanized_error(verb:, url:, response:, payload: nil)
  468. prefix = "Unable to process #{verb} request to elasticsearch URL '#{url}'."
  469. suffix = "\n\nResponse:\n#{response.inspect}\n\n"
  470. if payload.respond_to?(:to_json)
  471. suffix += "Payload:\n#{payload.to_json}"
  472. suffix += "\n\nPayload size: #{payload.to_json.bytesize / 1024 / 1024}M"
  473. else
  474. suffix += "Payload:\n#{payload.inspect}"
  475. end
  476. message = if response&.error&.match?('Connection refused') # rubocop:disable Zammad/DetectTranslatableString
  477. __("Elasticsearch is not reachable. It's possible that it's not running. Please check whether it is installed.")
  478. elsif url.end_with?('pipeline/zammad-attachment', 'pipeline=zammad-attachment') && response.code == 400
  479. __('The installed attachment plugin could not handle the request payload. Ensure that the correct attachment plugin is installed (ingest-attachment).')
  480. else
  481. __('Check the response and payload for detailed information:')
  482. end
  483. result = "#{prefix} #{message}#{suffix}"
  484. Rails.logger.error result.first(40_000)
  485. result
  486. end
  487. # add * on simple query like "somephrase23"
  488. def self.append_wildcard_to_simple_query(query)
  489. query = query.strip
  490. query += '*' if query.exclude?(':')
  491. query
  492. end
  493. =begin
  494. @param condition [Hash] search condition
  495. @param options [Hash] search options
  496. @option options [Integer] :from
  497. @option options [Integer] :limit
  498. @option options [Hash] :query_extension applied to ElasticSearch query
  499. @option options [Array<String>] :order_by ordering directions, desc or asc
  500. @option options [Array<String>] :sort_by fields to sort by
  501. @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.
  502. =end
  503. DEFAULT_QUERY_OPTIONS = {
  504. from: 0,
  505. limit: 10
  506. }.freeze
  507. def self.build_query(index, condition, options = {})
  508. options = DEFAULT_QUERY_OPTIONS.merge(options.deep_symbolize_keys)
  509. data = {
  510. from: options[:from],
  511. size: options[:limit],
  512. sort: search_by_index_sort(index: index, sort_by: options[:sort_by], order_by: options[:order_by], fulltext: options[:fulltext]),
  513. query: {
  514. bool: {
  515. must: []
  516. }
  517. }
  518. }
  519. if (extension = options[:query_extension])
  520. data[:query].deep_merge! extension.deep_dup
  521. end
  522. data[:query][:bool][:must].push condition
  523. if options[:ids].present?
  524. data[:query][:bool][:must].push({ ids: { values: options[:ids] } })
  525. end
  526. data
  527. end
  528. =begin
  529. refreshes all indexes to make previous request data visible in future requests
  530. SearchIndexBackend.refresh
  531. =end
  532. def self.refresh
  533. return if !enabled?
  534. url = "#{Setting.get('es_url')}/_all/_refresh"
  535. make_request_and_validate(url, method: :post)
  536. end
  537. =begin
  538. helper method for making HTTP calls
  539. @param url [String] url
  540. @option params [Hash] :data is a payload hash
  541. @option params [Symbol] :method is a HTTP method
  542. @option params [Integer] :open_timeout is HTTP request open timeout
  543. @option params [Integer] :read_timeout is HTTP request read timeout
  544. @return UserAgent response
  545. =end
  546. def self.make_request(url, data: {}, method: :get, open_timeout: 8, read_timeout: 180)
  547. Rails.logger.debug { "# curl -X #{method} \"#{url}\" " }
  548. Rails.logger.debug { "-d '#{data.to_json}'" } if data.present?
  549. options = {
  550. json: true,
  551. open_timeout: open_timeout,
  552. read_timeout: read_timeout,
  553. total_timeout: (open_timeout + read_timeout + 60),
  554. open_socket_tries: 3,
  555. user: Setting.get('es_user'),
  556. password: Setting.get('es_password'),
  557. verify_ssl: Setting.get('es_ssl_verify'),
  558. }
  559. response = UserAgent.send(method, url, data, options)
  560. Rails.logger.debug { "# #{response.code}" }
  561. response
  562. end
  563. =begin
  564. helper method for making HTTP calls and raising error if response was not success
  565. @param url [String] url
  566. @option args [Hash] see {make_request}
  567. @return [Boolean] always returns true. Raises error if something went wrong.
  568. =end
  569. def self.make_request_and_validate(url, **args)
  570. response = make_request(url, **args)
  571. return true if response.success?
  572. raise humanized_error(
  573. verb: args[:method],
  574. url: url,
  575. payload: args[:data],
  576. response: response
  577. )
  578. end
  579. =begin
  580. This function will return a index mapping based on the
  581. attributes of the database table of the existing object.
  582. mapping = SearchIndexBackend.get_mapping_properties_object(Ticket)
  583. Returns:
  584. mapping = {
  585. User: {
  586. properties: {
  587. firstname: {
  588. type: 'keyword',
  589. },
  590. }
  591. }
  592. }
  593. =end
  594. def self.get_mapping_properties_object(object)
  595. result = {
  596. properties: {}
  597. }
  598. store_columns = %w[preferences data]
  599. # for elasticsearch 6.x and later
  600. string_type = 'text'
  601. string_raw = { type: 'keyword', ignore_above: 5012 }
  602. boolean_raw = { type: 'boolean' }
  603. object.columns_hash.each do |key, value|
  604. if value.type == :string && value.limit && value.limit <= 5000 && store_columns.exclude?(key)
  605. result[:properties][key] = {
  606. type: string_type,
  607. fields: {
  608. keyword: string_raw,
  609. }
  610. }
  611. elsif value.type == :integer
  612. result[:properties][key] = {
  613. type: 'integer',
  614. }
  615. elsif value.type == :datetime || value.type == :date
  616. result[:properties][key] = {
  617. type: 'date',
  618. }
  619. elsif value.type == :boolean
  620. result[:properties][key] = {
  621. type: 'boolean',
  622. fields: {
  623. keyword: boolean_raw,
  624. }
  625. }
  626. elsif value.type == :binary
  627. result[:properties][key] = {
  628. type: 'binary',
  629. }
  630. elsif value.type == :bigint
  631. result[:properties][key] = {
  632. type: 'long',
  633. }
  634. elsif value.type == :decimal
  635. result[:properties][key] = {
  636. type: 'float',
  637. }
  638. end
  639. end
  640. case object.name
  641. when 'Ticket'
  642. result[:properties][:article] = {
  643. type: 'nested',
  644. include_in_parent: true,
  645. }
  646. end
  647. result
  648. end
  649. # get es version
  650. def self.version
  651. @version ||= SearchIndexBackend.info&.dig('version', 'number')
  652. end
  653. def self.configured?
  654. Setting.get('es_url').present?
  655. end
  656. def self.model_indexable?(model_name)
  657. Models.indexable.any? { |m| m.name == model_name }
  658. end
  659. def self.default_model_settings
  660. {
  661. 'index.mapping.total_fields.limit' => 2000,
  662. }
  663. end
  664. def self.model_settings(model)
  665. settings = Setting.get('es_model_settings')[model.name] || {}
  666. default_model_settings.merge(settings)
  667. end
  668. def self.all_settings
  669. Models.indexable.each_with_object({}).to_h { |m| [m.name, model_settings(m)] }
  670. end
  671. def self.set_setting(model_name, key, value)
  672. raise "It is not possible to configure settings for the non-indexable model '#{model_name}'." if !model_indexable?(model_name)
  673. raise __("The required parameter 'key' is missing.") if key.blank?
  674. raise __("The required parameter 'value' is missing.") if value.blank?
  675. config = Setting.get('es_model_settings')
  676. config[model_name] ||= {}
  677. config[model_name][key] = value
  678. Setting.set('es_model_settings', config)
  679. end
  680. def self.unset_setting(model_name, key)
  681. raise "It is not possible to configure settings for the non-indexable model '#{model_name}'." if !model_indexable?(model_name)
  682. raise __("The required parameter 'key' is missing.") if key.blank?
  683. config = Setting.get('es_model_settings')
  684. config[model_name] ||= {}
  685. config[model_name].delete(key)
  686. Setting.set('es_model_settings', config)
  687. end
  688. def self.create_index(models = Models.indexable)
  689. models.each do |local_object|
  690. SearchIndexBackend.index(
  691. action: 'create',
  692. name: local_object.name,
  693. data: {
  694. mappings: SearchIndexBackend.get_mapping_properties_object(local_object),
  695. settings: model_settings(local_object),
  696. }
  697. )
  698. end
  699. end
  700. def self.drop_index(models = Models.indexable)
  701. models.each do |local_object|
  702. SearchIndexBackend.index(
  703. action: 'delete',
  704. name: local_object.name,
  705. )
  706. end
  707. end
  708. def self.create_object_index(object)
  709. models = Models.indexable.select { |c| c.to_s == object }
  710. create_index(models)
  711. end
  712. def self.drop_object_index(object)
  713. models = Models.indexable.select { |c| c.to_s == object }
  714. drop_index(models)
  715. end
  716. def self.pipeline(create: false)
  717. pipeline = Setting.get('es_pipeline')
  718. if create && pipeline.blank?
  719. pipeline = "zammad#{SecureRandom.uuid}"
  720. Setting.set('es_pipeline', pipeline)
  721. end
  722. pipeline
  723. end
  724. def self.pipeline_settings
  725. {
  726. ignore_failure: true,
  727. ignore_missing: true,
  728. }
  729. end
  730. def self.create_pipeline
  731. SearchIndexBackend.processors(
  732. "_ingest/pipeline/#{pipeline(create: true)}": [
  733. {
  734. action: 'delete',
  735. },
  736. {
  737. action: 'create',
  738. description: __('Extract zammad-attachment information from arrays'),
  739. processors: [
  740. {
  741. foreach: {
  742. field: 'article',
  743. processor: {
  744. foreach: {
  745. field: '_ingest._value.attachment',
  746. processor: {
  747. attachment: {
  748. target_field: '_ingest._value',
  749. field: '_ingest._value._content',
  750. }.merge(pipeline_settings),
  751. }
  752. }.merge(pipeline_settings),
  753. }
  754. }.merge(pipeline_settings),
  755. },
  756. {
  757. foreach: {
  758. field: 'attachment',
  759. processor: {
  760. attachment: {
  761. target_field: '_ingest._value',
  762. field: '_ingest._value._content',
  763. }.merge(pipeline_settings),
  764. }
  765. }.merge(pipeline_settings),
  766. }
  767. ]
  768. }
  769. ]
  770. )
  771. end
  772. def self.drop_pipeline
  773. return if pipeline.blank?
  774. SearchIndexBackend.processors(
  775. "_ingest/pipeline/#{pipeline}": [
  776. {
  777. action: 'delete',
  778. },
  779. ]
  780. )
  781. end
  782. # Simulate an empty response from ES.
  783. def self.fake_empty_es_aggregation_response
  784. {
  785. 'hits' => { 'total' => { 'value' => 0, 'relation' => 'eq' }, 'max_score' => nil, 'hits' => [] },
  786. 'aggregations' => { 'time_buckets' => { 'buckets' => [] } }
  787. }
  788. end
  789. end