search_index_backend.rb 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
  2. class SearchIndexBackend
  3. =begin
  4. info about used search index machine
  5. SearchIndexBackend.info
  6. =end
  7. def self.info
  8. url = Setting.get('es_url').to_s
  9. return if url.blank?
  10. response = make_request(url)
  11. if response.success?
  12. installed_version = response.data.dig('version', 'number')
  13. raise "Unable to get elasticsearch version from response: #{response.inspect}" if installed_version.blank?
  14. installed_version_parsed = Gem::Version.new(installed_version)
  15. version_supported = installed_version_parsed < Gem::Version.new('8')
  16. raise "Version #{installed_version} of configured elasticsearch is not supported." if !version_supported
  17. version_supported = installed_version_parsed >= Gem::Version.new('7.8')
  18. raise "Version #{installed_version} of configured elasticsearch is not supported." if !version_supported
  19. return response.data
  20. end
  21. raise humanized_error(
  22. verb: 'GET',
  23. url: url,
  24. response: response,
  25. )
  26. end
  27. =begin
  28. update processors
  29. SearchIndexBackend.processors(
  30. _ingest/pipeline/attachment: {
  31. description: 'Extract attachment information from arrays',
  32. processors: [
  33. {
  34. foreach: {
  35. field: 'ticket.articles.attachments',
  36. processor: {
  37. attachment: {
  38. target_field: '_ingest._value.attachment',
  39. field: '_ingest._value.data'
  40. }
  41. }
  42. }
  43. }
  44. ]
  45. }
  46. )
  47. =end
  48. def self.processors(data)
  49. data.each do |key, items|
  50. url = "#{Setting.get('es_url')}/#{key}"
  51. items.each do |item|
  52. if item[:action] == 'delete'
  53. response = make_request(url, method: :delete)
  54. next if response.success?
  55. next if response.code.to_s == '404'
  56. raise humanized_error(
  57. verb: 'DELETE',
  58. url: url,
  59. response: response,
  60. )
  61. end
  62. item.delete(:action)
  63. make_request_and_validate(url, data: item, method: :put)
  64. end
  65. end
  66. true
  67. end
  68. =begin
  69. create/update/delete index
  70. SearchIndexBackend.index(
  71. :action => 'create', # create/update/delete
  72. :name => 'Ticket',
  73. :data => {
  74. :mappings => {
  75. :Ticket => {
  76. :properties => {
  77. :articles => {
  78. :type => 'nested',
  79. :properties => {
  80. 'attachment' => { :type => 'attachment' }
  81. }
  82. }
  83. }
  84. }
  85. }
  86. }
  87. )
  88. SearchIndexBackend.index(
  89. :action => 'delete', # create/update/delete
  90. :name => 'Ticket',
  91. )
  92. =end
  93. def self.index(data)
  94. url = build_url(type: data[:name], with_pipeline: false, with_document_type: false)
  95. return if url.blank?
  96. if data[:action] && data[:action] == 'delete'
  97. return SearchIndexBackend.remove(data[:name])
  98. end
  99. make_request_and_validate(url, data: data[:data], method: :put)
  100. end
  101. =begin
  102. add new object to search index
  103. SearchIndexBackend.add('Ticket', some_data_object)
  104. =end
  105. def self.add(type, data)
  106. url = build_url(type: type, object_id: data['id'])
  107. return if url.blank?
  108. make_request_and_validate(url, data: data, method: :post)
  109. end
  110. =begin
  111. This function updates specifc attributes of an index based on a query.
  112. data = {
  113. organization: {
  114. name: "Zammad Foundation"
  115. }
  116. }
  117. where = {
  118. organization_id: 1
  119. }
  120. SearchIndexBackend.update_by_query('Ticket', data, where)
  121. =end
  122. def self.update_by_query(type, data, where)
  123. return if data.blank?
  124. return if where.blank?
  125. url = build_url(type: type, action: '_update_by_query', with_pipeline: false, with_document_type: false, url_params: { conflicts: 'proceed' })
  126. return if url.blank?
  127. script_list = []
  128. data.each do |key, _value|
  129. script_list.push("ctx._source.#{key}=params.#{key}")
  130. end
  131. data = {
  132. script: {
  133. lang: 'painless',
  134. source: script_list.join(';'),
  135. params: data,
  136. },
  137. query: {
  138. term: where,
  139. },
  140. }
  141. make_request_and_validate(url, data: data, method: :post, read_timeout: 10.minutes)
  142. end
  143. =begin
  144. remove whole data from index
  145. SearchIndexBackend.remove('Ticket', 123)
  146. SearchIndexBackend.remove('Ticket')
  147. =end
  148. def self.remove(type, o_id = nil)
  149. url = if o_id
  150. build_url(type: type, object_id: o_id, with_pipeline: false, with_document_type: true)
  151. else
  152. build_url(type: type, object_id: o_id, with_pipeline: false, with_document_type: false)
  153. end
  154. return if url.blank?
  155. response = make_request(url, method: :delete)
  156. return true if response.success?
  157. return true if response.code.to_s == '400'
  158. humanized_error = humanized_error(
  159. verb: 'DELETE',
  160. url: url,
  161. response: response,
  162. )
  163. Rails.logger.warn "Can't delete index: #{humanized_error}"
  164. false
  165. end
  166. =begin
  167. @param query [String] search query
  168. @param index [String, Array<String>] indexes to search in (see search_by_index)
  169. @param options [Hash] search options (see build_query)
  170. @return search result
  171. @example Sample queries
  172. result = SearchIndexBackend.search('search query', ['User', 'Organization'], limit: limit)
  173. - result = SearchIndexBackend.search('search query', 'User', limit: limit)
  174. result = SearchIndexBackend.search('search query', 'User', limit: limit, sort_by: ['updated_at'], order_by: ['desc'])
  175. result = SearchIndexBackend.search('search query', 'User', limit: limit, sort_by: ['active', updated_at'], order_by: ['desc', 'desc'])
  176. result = [
  177. {
  178. :id => 123,
  179. :type => 'User',
  180. },
  181. {
  182. :id => 125,
  183. :type => 'User',
  184. },
  185. {
  186. :id => 15,
  187. :type => 'Organization',
  188. }
  189. ]
  190. =end
  191. def self.search(query, index, options = {})
  192. if !index.is_a? Array
  193. return search_by_index(query, index, options)
  194. end
  195. index
  196. .filter_map { |local_index| search_by_index(query, local_index, options) }
  197. .flatten(1)
  198. end
  199. =begin
  200. @param query [String] search query
  201. @param index [String] index name
  202. @param options [Hash] search options (see build_query)
  203. @return search result
  204. =end
  205. def self.search_by_index(query, index, options = {})
  206. return [] if query.blank?
  207. url = build_url(type: index, action: '_search', with_pipeline: false, with_document_type: true)
  208. return [] if url.blank?
  209. # real search condition
  210. condition = {
  211. 'query_string' => {
  212. 'query' => append_wildcard_to_simple_query(query),
  213. 'time_zone' => Setting.get('timezone_default').presence || 'UTC',
  214. 'default_operator' => 'AND',
  215. 'analyze_wildcard' => true,
  216. }
  217. }
  218. if (fields = options.dig(:highlight_fields_by_indexes, index.to_sym))
  219. condition['query_string']['fields'] = fields
  220. end
  221. query_data = build_query(condition, options)
  222. if (fields = options.dig(:highlight_fields_by_indexes, index.to_sym))
  223. fields_for_highlight = fields.index_with { |_elem| {} }
  224. query_data[:highlight] = { fields: fields_for_highlight }
  225. end
  226. response = make_request(url, data: query_data)
  227. if !response.success?
  228. Rails.logger.error humanized_error(
  229. verb: 'GET',
  230. url: url,
  231. payload: query_data,
  232. response: response,
  233. )
  234. return []
  235. end
  236. data = response.data&.dig('hits', 'hits')
  237. return [] if !data
  238. data.map do |item|
  239. Rails.logger.debug { "... #{item['_type']} #{item['_id']}" }
  240. output = {
  241. id: item['_id'],
  242. type: index,
  243. }
  244. if options.dig(:highlight_fields_by_indexes, index.to_sym)
  245. output[:highlight] = item['highlight']
  246. end
  247. output
  248. end
  249. end
  250. def self.search_by_index_sort(sort_by = nil, order_by = nil)
  251. result = []
  252. sort_by&.each_with_index do |value, index|
  253. next if value.blank?
  254. next if order_by&.at(index).blank?
  255. # for sorting values use .keyword values (no analyzer is used - plain values)
  256. if value !~ %r{\.} && value !~ %r{_(time|date|till|id|ids|at)$}
  257. value += '.keyword'
  258. end
  259. result.push(
  260. value => {
  261. order: order_by[index],
  262. },
  263. )
  264. end
  265. if result.blank?
  266. result.push(
  267. updated_at: {
  268. order: 'desc',
  269. },
  270. )
  271. end
  272. result.push('_score')
  273. result
  274. end
  275. =begin
  276. get count of tickets and tickets which match on selector
  277. result = SearchIndexBackend.selectors(index, selector)
  278. example with a simple search:
  279. result = SearchIndexBackend.selectors('Ticket', { 'category' => { 'operator' => 'is', 'value' => 'aa::ab' } })
  280. result = [
  281. { id: 1, type: 'Ticket' },
  282. { id: 2, type: 'Ticket' },
  283. { id: 3, type: 'Ticket' },
  284. ]
  285. you also can get aggregations
  286. result = SearchIndexBackend.selectors(index, selector, options, aggs_interval)
  287. example for aggregations within one year
  288. aggs_interval = {
  289. from: '2015-01-01',
  290. to: '2015-12-31',
  291. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  292. field: 'created_at',
  293. }
  294. options = {
  295. limit: 123,
  296. current_user: User.find(123),
  297. }
  298. result = SearchIndexBackend.selectors('Ticket', { 'category' => { 'operator' => 'is', 'value' => 'aa::ab' } }, options, aggs_interval)
  299. result = {
  300. hits:{
  301. total:4819,
  302. },
  303. aggregations:{
  304. time_buckets:{
  305. buckets:[
  306. {
  307. key_as_string:"2014-10-01T00:00:00.000Z",
  308. key:1412121600000,
  309. doc_count:420
  310. },
  311. {
  312. key_as_string:"2014-11-01T00:00:00.000Z",
  313. key:1414800000000,
  314. doc_count:561
  315. },
  316. ...
  317. ]
  318. }
  319. }
  320. }
  321. =end
  322. def self.selectors(index, selectors = nil, options = {}, aggs_interval = nil)
  323. raise 'no selectors given' if !selectors
  324. url = build_url(type: index, action: '_search', with_pipeline: false, with_document_type: true)
  325. return if url.blank?
  326. data = selector2query(selectors, options, aggs_interval)
  327. response = make_request(url, data: data)
  328. if !response.success?
  329. raise humanized_error(
  330. verb: 'GET',
  331. url: url,
  332. payload: data,
  333. response: response,
  334. )
  335. end
  336. Rails.logger.debug { response.data.to_json }
  337. if aggs_interval.blank? || aggs_interval[:interval].blank?
  338. ticket_ids = []
  339. response.data['hits']['hits'].each do |item|
  340. ticket_ids.push item['_id']
  341. end
  342. # in lower ES 6 versions, we get total count directly, in higher
  343. # versions we need to pick it from total has
  344. count = response.data['hits']['total']
  345. if response.data['hits']['total'].class != Integer
  346. count = response.data['hits']['total']['value']
  347. end
  348. return {
  349. count: count,
  350. ticket_ids: ticket_ids,
  351. }
  352. end
  353. response.data
  354. end
  355. DEFAULT_SELECTOR_OPTIONS = {
  356. limit: 10
  357. }.freeze
  358. def self.selector2query(selector, options, aggs_interval)
  359. options = DEFAULT_QUERY_OPTIONS.merge(options.deep_symbolize_keys)
  360. current_user = options[:current_user]
  361. current_user_id = UserInfo.current_user_id
  362. if current_user
  363. current_user_id = current_user.id
  364. end
  365. query_must = []
  366. query_must_not = []
  367. relative_map = {
  368. day: 'd',
  369. year: 'y',
  370. month: 'M',
  371. hour: 'h',
  372. minute: 'm',
  373. }
  374. if selector.present?
  375. operators_is_isnot = ['is', 'is not']
  376. selector.each do |key, data|
  377. data = data.clone
  378. table, key_tmp = key.split('.')
  379. if key_tmp.blank?
  380. key_tmp = table
  381. table = 'ticket'
  382. end
  383. wildcard_or_term = 'term'
  384. if data['value'].is_a?(Array)
  385. wildcard_or_term = 'terms'
  386. end
  387. t = {}
  388. # use .keyword in case of compare exact values
  389. if data['operator'] == 'is' || data['operator'] == 'is not'
  390. case data['pre_condition']
  391. when 'not_set'
  392. data['value'] = if key_tmp.match?(%r{^(created_by|updated_by|owner|customer|user)_id})
  393. 1
  394. end
  395. when 'current_user.id'
  396. raise "Use current_user.id in selector, but no current_user is set #{data.inspect}" if !current_user_id
  397. data['value'] = []
  398. wildcard_or_term = 'terms'
  399. if key_tmp == 'out_of_office_replacement_id'
  400. data['value'].push User.find(current_user_id).out_of_office_agent_of.pluck(:id)
  401. else
  402. data['value'].push current_user_id
  403. end
  404. when 'current_user.organization_id'
  405. raise "Use current_user.id in selector, but no current_user is set #{data.inspect}" if !current_user_id
  406. user = User.find_by(id: current_user_id)
  407. data['value'] = user.organization_id
  408. end
  409. if data['value'].is_a?(Array)
  410. data['value'].each do |value|
  411. next if !value.is_a?(String) || value !~ %r{[A-z]}
  412. key_tmp += '.keyword'
  413. break
  414. end
  415. elsif data['value'].is_a?(String) && %r{[A-z]}.match?(data['value'])
  416. key_tmp += '.keyword'
  417. end
  418. end
  419. # use .keyword and wildcard search in cases where query contains non A-z chars
  420. if data['operator'] == 'contains' || data['operator'] == 'contains not'
  421. if data['value'].is_a?(Array)
  422. data['value'].each_with_index do |value, index|
  423. next if !value.is_a?(String) || value !~ %r{[A-z]}
  424. data['value'][index] = "*#{value}*"
  425. key_tmp += '.keyword'
  426. wildcard_or_term = 'wildcards'
  427. break
  428. end
  429. elsif data['value'].is_a?(String) && %r{[A-z]}.match?(data['value'])
  430. data['value'] = "*#{data['value']}*"
  431. key_tmp += '.keyword'
  432. wildcard_or_term = 'wildcard'
  433. end
  434. end
  435. # for pre condition not_set we want to check if values are defined for the object by exists
  436. if data['pre_condition'] == 'not_set' && operators_is_isnot.include?(data['operator']) && data['value'].nil?
  437. t['exists'] = {
  438. field: key_tmp,
  439. }
  440. case data['operator']
  441. when 'is'
  442. query_must_not.push t
  443. when 'is not'
  444. query_must.push t
  445. end
  446. next
  447. end
  448. if table != 'ticket'
  449. key_tmp = "#{table}.#{key_tmp}"
  450. end
  451. # is/is not/contains/contains not
  452. case data['operator']
  453. when 'is', 'is not', 'contains', 'contains not'
  454. t[wildcard_or_term] = {}
  455. t[wildcard_or_term][key_tmp] = data['value']
  456. case data['operator']
  457. when 'is', 'contains'
  458. query_must.push t
  459. when 'is not', 'contains not'
  460. query_must_not.push t
  461. end
  462. when 'contains all', 'contains one', 'contains all not', 'contains one not'
  463. values = data['value'].split(',').map(&:strip)
  464. t[:query_string] = {}
  465. case data['operator']
  466. when 'contains all'
  467. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  468. query_must.push t
  469. when 'contains one not'
  470. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  471. query_must_not.push t
  472. when 'contains one'
  473. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  474. query_must.push t
  475. when 'contains all not'
  476. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  477. query_must_not.push t
  478. end
  479. # within last/within next (relative)
  480. when 'within last (relative)', 'within next (relative)'
  481. range = relative_map[data['range'].to_sym]
  482. if range.blank?
  483. raise "Invalid relative_map for range '#{data['range']}'."
  484. end
  485. t[:range] = {}
  486. t[:range][key_tmp] = {}
  487. if data['operator'] == 'within last (relative)'
  488. t[:range][key_tmp][:gte] = "now-#{data['value']}#{range}"
  489. else
  490. t[:range][key_tmp][:lt] = "now+#{data['value']}#{range}"
  491. end
  492. query_must.push t
  493. # before/after (relative)
  494. when 'before (relative)', 'after (relative)'
  495. range = relative_map[data['range'].to_sym]
  496. if range.blank?
  497. raise "Invalid relative_map for range '#{data['range']}'."
  498. end
  499. t[:range] = {}
  500. t[:range][key_tmp] = {}
  501. if data['operator'] == 'before (relative)'
  502. t[:range][key_tmp][:lt] = "now-#{data['value']}#{range}"
  503. else
  504. t[:range][key_tmp][:gt] = "now+#{data['value']}#{range}"
  505. end
  506. query_must.push t
  507. # till/from (relative)
  508. when 'till (relative)', 'from (relative)'
  509. range = relative_map[data['range'].to_sym]
  510. if range.blank?
  511. raise "Invalid relative_map for range '#{data['range']}'."
  512. end
  513. t[:range] = {}
  514. t[:range][key_tmp] = {}
  515. if data['operator'] == 'till (relative)'
  516. t[:range][key_tmp][:lt] = "now+#{data['value']}#{range}"
  517. else
  518. t[:range][key_tmp][:gt] = "now-#{data['value']}#{range}"
  519. end
  520. query_must.push t
  521. # before/after (absolute)
  522. when 'before (absolute)', 'after (absolute)'
  523. t[:range] = {}
  524. t[:range][key_tmp] = {}
  525. if data['operator'] == 'before (absolute)'
  526. t[:range][key_tmp][:lt] = (data['value'])
  527. else
  528. t[:range][key_tmp][:gt] = (data['value'])
  529. end
  530. query_must.push t
  531. else
  532. raise "unknown operator '#{data['operator']}' for #{key}"
  533. end
  534. end
  535. end
  536. data = {
  537. query: {},
  538. size: options[:limit],
  539. }
  540. # add aggs to filter
  541. if aggs_interval.present?
  542. if aggs_interval[:interval].present?
  543. data[:size] = 0
  544. data[:aggs] = {
  545. time_buckets: {
  546. date_histogram: {
  547. field: aggs_interval[:field],
  548. interval: aggs_interval[:interval],
  549. }
  550. }
  551. }
  552. if aggs_interval[:timezone].present?
  553. data[:aggs][:time_buckets][:date_histogram][:time_zone] = aggs_interval[:timezone]
  554. end
  555. end
  556. r = {}
  557. r[:range] = {}
  558. r[:range][aggs_interval[:field]] = {
  559. from: aggs_interval[:from],
  560. to: aggs_interval[:to],
  561. }
  562. query_must.push r
  563. end
  564. data[:query][:bool] ||= {}
  565. if query_must.present?
  566. data[:query][:bool][:must] = query_must
  567. end
  568. if query_must_not.present?
  569. data[:query][:bool][:must_not] = query_must_not
  570. end
  571. # add sort
  572. if aggs_interval.present? && aggs_interval[:field].present? && aggs_interval[:interval].blank?
  573. sort = []
  574. sort[0] = {}
  575. sort[0][aggs_interval[:field]] = {
  576. order: 'desc'
  577. }
  578. sort[1] = '_score'
  579. data['sort'] = sort
  580. else
  581. data['sort'] = search_by_index_sort(options[:sort_by], options[:order_by])
  582. end
  583. data
  584. end
  585. =begin
  586. return true if backend is configured
  587. result = SearchIndexBackend.enabled?
  588. =end
  589. def self.enabled?
  590. return false if Setting.get('es_url').blank?
  591. true
  592. end
  593. def self.build_index_name(index = nil)
  594. local_index = "#{Setting.get('es_index')}_#{Rails.env}"
  595. return local_index if index.blank?
  596. "#{local_index}_#{index.underscore.tr('/', '_')}"
  597. end
  598. =begin
  599. generate url for index or document access (only for internal use)
  600. # url to access single document in index (in case with_pipeline or not)
  601. url = SearchIndexBackend.build_url(type: 'User', object_id: 123, with_pipeline: true)
  602. # url to access whole index
  603. url = SearchIndexBackend.build_url(type: 'User')
  604. # url to access document definition in index (only es6 and higher)
  605. url = SearchIndexBackend.build_url(type: 'User', with_pipeline: false, with_document_type: true)
  606. # base url
  607. url = SearchIndexBackend.build_url
  608. =end
  609. # rubocop:disable Metrics/ParameterLists
  610. def self.build_url(type: nil, action: nil, object_id: nil, with_pipeline: true, with_document_type: true, url_params: {})
  611. # rubocop:enable Metrics/ParameterLists
  612. return if !SearchIndexBackend.enabled?
  613. # set index
  614. index = build_index_name(type)
  615. # add pipeline if needed
  616. if index && with_pipeline == true
  617. url_pipline = Setting.get('es_pipeline')
  618. if url_pipline.present?
  619. url_params['pipeline'] = url_pipline
  620. end
  621. end
  622. # prepare url params
  623. params_string = ''
  624. if url_params.present?
  625. params_string = "?#{URI.encode_www_form(url_params)}"
  626. end
  627. url = Setting.get('es_url')
  628. return "#{url}#{params_string}" if index.blank?
  629. # add type information
  630. url = "#{url}/#{index}"
  631. # add document type
  632. if with_document_type
  633. url = "#{url}/_doc"
  634. end
  635. # add action
  636. if action
  637. url = "#{url}/#{action}"
  638. end
  639. # add object id
  640. if object_id.present?
  641. url = "#{url}/#{object_id}"
  642. end
  643. "#{url}#{params_string}"
  644. end
  645. def self.humanized_error(verb:, url:, response:, payload: nil)
  646. prefix = "Unable to process #{verb} request to elasticsearch URL '#{url}'."
  647. suffix = "\n\nResponse:\n#{response.inspect}\n\n"
  648. if payload.respond_to?(:to_json)
  649. suffix += "Payload:\n#{payload.to_json}"
  650. suffix += "\n\nPayload size: #{payload.to_json.bytesize / 1024 / 1024}M"
  651. else
  652. suffix += "Payload:\n#{payload.inspect}"
  653. end
  654. message = if response&.error&.match?('Connection refused')
  655. "Elasticsearch is not reachable, probably because it's not running or even installed."
  656. elsif url.end_with?('pipeline/zammad-attachment', 'pipeline=zammad-attachment') && response.code == 400
  657. 'The installed attachment plugin could not handle the request payload. Ensure that the correct attachment plugin is installed (ingest-attachment).'
  658. else
  659. 'Check the response and payload for detailed information: '
  660. end
  661. result = "#{prefix} #{message}#{suffix}"
  662. Rails.logger.error result.first(40_000)
  663. result
  664. end
  665. # add * on simple query like "somephrase23"
  666. def self.append_wildcard_to_simple_query(query)
  667. query.strip!
  668. query += '*' if query.exclude?(':')
  669. query
  670. end
  671. =begin
  672. @param condition [Hash] search condition
  673. @param options [Hash] search options
  674. @option options [Integer] :from
  675. @option options [Integer] :limit
  676. @option options [Hash] :query_extension applied to ElasticSearch query
  677. @option options [Array<String>] :order_by ordering directions, desc or asc
  678. @option options [Array<String>] :sort_by fields to sort by
  679. =end
  680. DEFAULT_QUERY_OPTIONS = {
  681. from: 0,
  682. limit: 10
  683. }.freeze
  684. def self.build_query(condition, options = {})
  685. options = DEFAULT_QUERY_OPTIONS.merge(options.deep_symbolize_keys)
  686. data = {
  687. from: options[:from],
  688. size: options[:limit],
  689. sort: search_by_index_sort(options[:sort_by], options[:order_by]),
  690. query: {
  691. bool: {
  692. must: []
  693. }
  694. }
  695. }
  696. if (extension = options[:query_extension])
  697. data[:query].deep_merge! extension.deep_dup
  698. end
  699. data[:query][:bool][:must].push condition
  700. data
  701. end
  702. =begin
  703. refreshes all indexes to make previous request data visible in future requests
  704. SearchIndexBackend.refresh
  705. =end
  706. def self.refresh
  707. return if !enabled?
  708. url = "#{Setting.get('es_url')}/_all/_refresh"
  709. make_request_and_validate(url, method: :post)
  710. end
  711. =begin
  712. helper method for making HTTP calls
  713. @param url [String] url
  714. @option params [Hash] :data is a payload hash
  715. @option params [Symbol] :method is a HTTP method
  716. @option params [Integer] :open_timeout is HTTP request open timeout
  717. @option params [Integer] :read_timeout is HTTP request read timeout
  718. @return UserAgent response
  719. =end
  720. def self.make_request(url, data: {}, method: :get, open_timeout: 8, read_timeout: 180)
  721. Rails.logger.debug { "# curl -X #{method} \"#{url}\" " }
  722. Rails.logger.debug { "-d '#{data.to_json}'" } if data.present?
  723. options = {
  724. json: true,
  725. open_timeout: open_timeout,
  726. read_timeout: read_timeout,
  727. total_timeout: (open_timeout + read_timeout + 60),
  728. open_socket_tries: 3,
  729. user: Setting.get('es_user'),
  730. password: Setting.get('es_password'),
  731. }
  732. response = UserAgent.send(method, url, data, options)
  733. Rails.logger.debug { "# #{response.code}" }
  734. response
  735. end
  736. =begin
  737. helper method for making HTTP calls and raising error if response was not success
  738. @param url [String] url
  739. @option args [Hash] see {make_request}
  740. @return [Boolean] always returns true. Raises error if something went wrong.
  741. =end
  742. def self.make_request_and_validate(url, **args)
  743. response = make_request(url, **args)
  744. return true if response.success?
  745. raise humanized_error(
  746. verb: args[:method],
  747. url: url,
  748. payload: args[:data],
  749. response: response
  750. )
  751. end
  752. =begin
  753. This function will return a index mapping based on the
  754. attributes of the database table of the existing object.
  755. mapping = SearchIndexBackend.get_mapping_properties_object(Ticket)
  756. Returns:
  757. mapping = {
  758. User: {
  759. properties: {
  760. firstname: {
  761. type: 'keyword',
  762. },
  763. }
  764. }
  765. }
  766. =end
  767. def self.get_mapping_properties_object(object)
  768. name = '_doc'
  769. result = {
  770. name => {
  771. properties: {}
  772. }
  773. }
  774. store_columns = %w[preferences data]
  775. # for elasticsearch 6.x and later
  776. string_type = 'text'
  777. string_raw = { type: 'keyword', ignore_above: 5012 }
  778. boolean_raw = { type: 'boolean' }
  779. object.columns_hash.each do |key, value|
  780. if value.type == :string && value.limit && value.limit <= 5000 && store_columns.exclude?(key)
  781. result[name][:properties][key] = {
  782. type: string_type,
  783. fields: {
  784. keyword: string_raw,
  785. }
  786. }
  787. elsif value.type == :integer
  788. result[name][:properties][key] = {
  789. type: 'integer',
  790. }
  791. elsif value.type == :datetime || value.type == :date
  792. result[name][:properties][key] = {
  793. type: 'date',
  794. }
  795. elsif value.type == :boolean
  796. result[name][:properties][key] = {
  797. type: 'boolean',
  798. fields: {
  799. keyword: boolean_raw,
  800. }
  801. }
  802. elsif value.type == :binary
  803. result[name][:properties][key] = {
  804. type: 'binary',
  805. }
  806. elsif value.type == :bigint
  807. result[name][:properties][key] = {
  808. type: 'long',
  809. }
  810. elsif value.type == :decimal
  811. result[name][:properties][key] = {
  812. type: 'float',
  813. }
  814. end
  815. end
  816. case object.name
  817. when 'Ticket'
  818. result[name][:_source] = {
  819. excludes: ['article.attachment']
  820. }
  821. result[name][:properties][:article] = {
  822. type: 'nested',
  823. include_in_parent: true,
  824. }
  825. when 'KnowledgeBase::Answer::Translation'
  826. result[name][:_source] = {
  827. excludes: ['attachment']
  828. }
  829. end
  830. return result if type_in_mapping?
  831. result[name]
  832. end
  833. # get es version
  834. def self.version
  835. @version ||= begin
  836. info = SearchIndexBackend.info
  837. number = nil
  838. if info.present?
  839. number = info['version']['number'].to_s
  840. end
  841. number
  842. end
  843. end
  844. def self.version_int
  845. number = version
  846. return 0 if !number
  847. number_split = version.split('.')
  848. "#{number_split[0]}#{format('%<minor>03d', minor: number_split[1])}#{format('%<patch>03d', patch: number_split[2])}".to_i
  849. end
  850. def self.version_supported?
  851. # only versions greater/equal than 6.5.0 are supported
  852. return if version_int < 6_005_000
  853. true
  854. end
  855. # no type in mapping
  856. def self.type_in_mapping?
  857. return true if version_int < 7_000_000
  858. false
  859. end
  860. # is es configured?
  861. def self.configured?
  862. return false if Setting.get('es_url').blank?
  863. true
  864. end
  865. def self.settings
  866. {
  867. 'index.mapping.total_fields.limit': 2000,
  868. }
  869. end
  870. def self.create_index(models = Models.indexable)
  871. models.each do |local_object|
  872. SearchIndexBackend.index(
  873. action: 'create',
  874. name: local_object.name,
  875. data: {
  876. mappings: SearchIndexBackend.get_mapping_properties_object(local_object),
  877. settings: SearchIndexBackend.settings,
  878. }
  879. )
  880. end
  881. end
  882. def self.drop_index(models = Models.indexable)
  883. models.each do |local_object|
  884. SearchIndexBackend.index(
  885. action: 'delete',
  886. name: local_object.name,
  887. )
  888. end
  889. end
  890. def self.create_object_index(object)
  891. models = Models.indexable.select { |c| c.to_s == object }
  892. create_index(models)
  893. end
  894. def self.drop_object_index(object)
  895. models = Models.indexable.select { |c| c.to_s == object }
  896. drop_index(models)
  897. end
  898. def self.pipeline(create: false)
  899. pipeline = Setting.get('es_pipeline')
  900. if create && pipeline.blank?
  901. pipeline = "zammad#{rand(999_999_999_999)}"
  902. Setting.set('es_pipeline', pipeline)
  903. end
  904. pipeline
  905. end
  906. def self.pipeline_settings
  907. {
  908. ignore_failure: true,
  909. ignore_missing: true,
  910. }
  911. end
  912. def self.create_pipeline
  913. SearchIndexBackend.processors(
  914. "_ingest/pipeline/#{pipeline(create: true)}": [
  915. {
  916. action: 'delete',
  917. },
  918. {
  919. action: 'create',
  920. description: 'Extract zammad-attachment information from arrays',
  921. processors: [
  922. {
  923. foreach: {
  924. field: 'article',
  925. processor: {
  926. foreach: {
  927. field: '_ingest._value.attachment',
  928. processor: {
  929. attachment: {
  930. target_field: '_ingest._value',
  931. field: '_ingest._value._content',
  932. }.merge(pipeline_settings),
  933. }
  934. }.merge(pipeline_settings),
  935. }
  936. }.merge(pipeline_settings),
  937. },
  938. {
  939. foreach: {
  940. field: 'attachment',
  941. processor: {
  942. attachment: {
  943. target_field: '_ingest._value',
  944. field: '_ingest._value._content',
  945. }.merge(pipeline_settings),
  946. }
  947. }.merge(pipeline_settings),
  948. }
  949. ]
  950. }
  951. ]
  952. )
  953. end
  954. def self.drop_pipeline
  955. return if pipeline.blank?
  956. SearchIndexBackend.processors(
  957. "_ingest/pipeline/#{pipeline}": [
  958. {
  959. action: 'delete',
  960. },
  961. ]
  962. )
  963. end
  964. end