search_index_backend.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. # Copyright (C) 2012-2016 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. Rails.logger.info "# curl -X GET \"#{url}\""
  11. response = UserAgent.get(
  12. url,
  13. {},
  14. {
  15. json: true,
  16. open_timeout: 8,
  17. read_timeout: 12,
  18. user: Setting.get('es_user'),
  19. password: Setting.get('es_password'),
  20. }
  21. )
  22. Rails.logger.info "# #{response.code}"
  23. if response.success?
  24. installed_version = response.data.dig('version', 'number')
  25. raise "Unable to get elasticsearch version from response: #{response.inspect}" if installed_version.blank?
  26. version_supported = Gem::Version.new(installed_version) < Gem::Version.new('5.7')
  27. raise "Version #{installed_version} of configured elasticsearch is not supported" if !version_supported
  28. return response.data
  29. end
  30. raise humanized_error(
  31. verb: 'GET',
  32. url: url,
  33. response: response,
  34. )
  35. end
  36. =begin
  37. update processors
  38. SearchIndexBackend.processors(
  39. _ingest/pipeline/attachment: {
  40. description: 'Extract attachment information from arrays',
  41. processors: [
  42. {
  43. foreach: {
  44. field: 'ticket.articles.attachments',
  45. processor: {
  46. attachment: {
  47. target_field: '_ingest._value.attachment',
  48. field: '_ingest._value.data'
  49. }
  50. }
  51. }
  52. }
  53. ]
  54. }
  55. )
  56. =end
  57. def self.processors(data)
  58. data.each do |key, items|
  59. url = "#{Setting.get('es_url')}/#{key}"
  60. items.each do |item|
  61. if item[:action] == 'delete'
  62. Rails.logger.info "# curl -X DELETE \"#{url}\""
  63. response = UserAgent.delete(
  64. url,
  65. {
  66. json: true,
  67. open_timeout: 8,
  68. read_timeout: 12,
  69. user: Setting.get('es_user'),
  70. password: Setting.get('es_password'),
  71. }
  72. )
  73. Rails.logger.info "# #{response.code}"
  74. next if response.success?
  75. next if response.code.to_s == '404'
  76. raise humanized_error(
  77. verb: 'DELETE',
  78. url: url,
  79. response: response,
  80. )
  81. end
  82. Rails.logger.info "# curl -X PUT \"#{url}\" \\"
  83. Rails.logger.debug { "-d '#{data.to_json}'" }
  84. item.delete(:action)
  85. response = UserAgent.put(
  86. url,
  87. item,
  88. {
  89. json: true,
  90. open_timeout: 8,
  91. read_timeout: 12,
  92. user: Setting.get('es_user'),
  93. password: Setting.get('es_password'),
  94. }
  95. )
  96. Rails.logger.info "# #{response.code}"
  97. next if response.success?
  98. raise humanized_error(
  99. verb: 'PUT',
  100. url: url,
  101. payload: item,
  102. response: response,
  103. )
  104. end
  105. end
  106. true
  107. end
  108. =begin
  109. create/update/delete index
  110. SearchIndexBackend.index(
  111. :action => 'create', # create/update/delete
  112. :data => {
  113. :mappings => {
  114. :Ticket => {
  115. :properties => {
  116. :articles => {
  117. :type => 'nested',
  118. :properties => {
  119. 'attachment' => { :type => 'attachment' }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. )
  127. SearchIndexBackend.index(
  128. :action => 'delete', # create/update/delete
  129. :name => 'Ticket', # optional
  130. )
  131. SearchIndexBackend.index(
  132. :action => 'delete', # create/update/delete
  133. )
  134. =end
  135. def self.index(data)
  136. url = build_url(data[:name])
  137. return if url.blank?
  138. if data[:action] && data[:action] == 'delete'
  139. return SearchIndexBackend.remove(data[:name])
  140. end
  141. Rails.logger.info "# curl -X PUT \"#{url}\" \\"
  142. Rails.logger.debug { "-d '#{data[:data].to_json}'" }
  143. # note that we use a high read timeout here because
  144. # otherwise the request will be retried (underhand)
  145. # which leads to an "index_already_exists_exception"
  146. # HTTP 400 status error
  147. # see: https://github.com/ankane/the-ultimate-guide-to-ruby-timeouts/issues/8
  148. # Improving the Elasticsearch config is probably the proper solution
  149. response = UserAgent.put(
  150. url,
  151. data[:data],
  152. {
  153. json: true,
  154. open_timeout: 8,
  155. read_timeout: 30,
  156. user: Setting.get('es_user'),
  157. password: Setting.get('es_password'),
  158. }
  159. )
  160. Rails.logger.info "# #{response.code}"
  161. return true if response.success?
  162. raise humanized_error(
  163. verb: 'PUT',
  164. url: url,
  165. payload: data[:data],
  166. response: response,
  167. )
  168. end
  169. =begin
  170. add new object to search index
  171. SearchIndexBackend.add('Ticket', some_data_object)
  172. =end
  173. def self.add(type, data)
  174. url = build_url(type, data['id'])
  175. return if url.blank?
  176. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  177. Rails.logger.debug { "-d '#{data.to_json}'" }
  178. response = UserAgent.post(
  179. url,
  180. data,
  181. {
  182. json: true,
  183. open_timeout: 8,
  184. read_timeout: 16,
  185. user: Setting.get('es_user'),
  186. password: Setting.get('es_password'),
  187. }
  188. )
  189. Rails.logger.info "# #{response.code}"
  190. return true if response.success?
  191. raise humanized_error(
  192. verb: 'POST',
  193. url: url,
  194. payload: data,
  195. response: response,
  196. )
  197. end
  198. =begin
  199. remove whole data from index
  200. SearchIndexBackend.remove('Ticket', 123)
  201. SearchIndexBackend.remove('Ticket')
  202. =end
  203. def self.remove(type, o_id = nil)
  204. url = build_url(type, o_id)
  205. return if url.blank?
  206. Rails.logger.info "# curl -X DELETE \"#{url}\""
  207. response = UserAgent.delete(
  208. url,
  209. {
  210. open_timeout: 8,
  211. read_timeout: 16,
  212. user: Setting.get('es_user'),
  213. password: Setting.get('es_password'),
  214. }
  215. )
  216. Rails.logger.info "# #{response.code}"
  217. return true if response.success?
  218. return true if response.code.to_s == '400'
  219. humanized_error = humanized_error(
  220. verb: 'DELETE',
  221. url: url,
  222. response: response,
  223. )
  224. Rails.logger.info "NOTICE: can't delete index: #{humanized_error}"
  225. false
  226. end
  227. =begin
  228. return search result
  229. result = SearchIndexBackend.search('search query', limit, ['User', 'Organization'])
  230. result = SearchIndexBackend.search('search query', limit, 'User')
  231. result = SearchIndexBackend.search('search query', limit, 'User', ['updated_at'], ['desc'])
  232. result = [
  233. {
  234. :id => 123,
  235. :type => 'User',
  236. },
  237. {
  238. :id => 125,
  239. :type => 'User',
  240. },
  241. {
  242. :id => 15,
  243. :type => 'Organization',
  244. }
  245. ]
  246. =end
  247. # rubocop:disable Metrics/ParameterLists
  248. def self.search(query, limit = 10, index = nil, query_extention = {}, from = 0, sort_by = [], order_by = [])
  249. # rubocop:enable Metrics/ParameterLists
  250. return [] if query.blank?
  251. if index.class == Array
  252. ids = []
  253. index.each do |local_index|
  254. local_ids = search_by_index(query, limit, local_index, query_extention, from, sort_by, order_by )
  255. ids = ids.concat(local_ids)
  256. end
  257. return ids
  258. end
  259. search_by_index(query, limit, index, query_extention, from, sort_by, order_by)
  260. end
  261. # rubocop:disable Metrics/ParameterLists
  262. def self.search_by_index(query, limit = 10, index = nil, query_extention = {}, from = 0, sort_by = [], order_by = [])
  263. # rubocop:enable Metrics/ParameterLists
  264. return [] if query.blank?
  265. url = build_url
  266. return if url.blank?
  267. url += if index
  268. if index.class == Array
  269. "/#{index.join(',')}/_search"
  270. else
  271. "/#{index}/_search"
  272. end
  273. else
  274. '/_search'
  275. end
  276. data = {}
  277. data['from'] = from
  278. data['size'] = limit
  279. data['sort'] = search_by_index_sort(sort_by, order_by)
  280. data['query'] = query_extention || {}
  281. data['query']['bool'] ||= {}
  282. data['query']['bool']['must'] ||= []
  283. # real search condition
  284. condition = {
  285. 'query_string' => {
  286. 'query' => append_wildcard_to_simple_query(query),
  287. 'default_operator' => 'AND',
  288. }
  289. }
  290. data['query']['bool']['must'].push condition
  291. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  292. Rails.logger.debug { " -d'#{data.to_json}'" }
  293. response = UserAgent.get(
  294. url,
  295. data,
  296. {
  297. json: true,
  298. open_timeout: 5,
  299. read_timeout: 14,
  300. user: Setting.get('es_user'),
  301. password: Setting.get('es_password'),
  302. }
  303. )
  304. Rails.logger.info "# #{response.code}"
  305. if !response.success?
  306. Rails.logger.error humanized_error(
  307. verb: 'GET',
  308. url: url,
  309. payload: data,
  310. response: response,
  311. )
  312. return []
  313. end
  314. data = response.data
  315. ids = []
  316. return ids if !data
  317. return ids if !data['hits']
  318. return ids if !data['hits']['hits']
  319. data['hits']['hits'].each do |item|
  320. Rails.logger.info "... #{item['_type']} #{item['_id']}"
  321. data = {
  322. id: item['_id'],
  323. type: item['_type'],
  324. }
  325. ids.push data
  326. end
  327. ids
  328. end
  329. def self.search_by_index_sort(sort_by = [], order_by = [])
  330. result = []
  331. sort_by.each_with_index do |value, index|
  332. next if value.blank?
  333. next if order_by[index].blank?
  334. if value !~ /\./ && value !~ /_(time|date|till|id|ids|at)$/
  335. value += '.raw'
  336. end
  337. result.push(
  338. value => {
  339. order: order_by[index],
  340. },
  341. )
  342. end
  343. if result.blank?
  344. result.push(
  345. updated_at: {
  346. order: 'desc',
  347. },
  348. )
  349. end
  350. # add sorting by active if active is not part of the query
  351. if result.flat_map(&:keys).exclude?(:active)
  352. result.unshift(
  353. active: {
  354. order: 'desc',
  355. },
  356. )
  357. end
  358. result.push('_score')
  359. result
  360. end
  361. =begin
  362. get count of tickets and tickets which match on selector
  363. aggs_interval = {
  364. from: '2015-01-01',
  365. to: '2015-12-31',
  366. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  367. field: 'created_at',
  368. }
  369. result = SearchIndexBackend.selectors(index, params[:condition], limit, current_user, aggs_interval)
  370. # for aggregations
  371. result = {
  372. hits:{
  373. total:4819,
  374. },
  375. aggregations:{
  376. time_buckets:{
  377. buckets:[
  378. {
  379. key_as_string:"2014-10-01T00:00:00.000Z",
  380. key:1412121600000,
  381. doc_count:420
  382. },
  383. {
  384. key_as_string:"2014-11-01T00:00:00.000Z",
  385. key:1414800000000,
  386. doc_count:561
  387. },
  388. ...
  389. ]
  390. }
  391. }
  392. }
  393. =end
  394. def self.selectors(index = nil, selectors = nil, limit = 10, current_user = nil, aggs_interval = nil)
  395. raise 'no selectors given' if !selectors
  396. url = build_url
  397. return if url.blank?
  398. url += if index
  399. if index.class == Array
  400. "/#{index.join(',')}/_search"
  401. else
  402. "/#{index}/_search"
  403. end
  404. else
  405. '/_search'
  406. end
  407. data = selector2query(selectors, current_user, aggs_interval, limit)
  408. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  409. Rails.logger.debug { " -d'#{data.to_json}'" }
  410. response = UserAgent.get(
  411. url,
  412. data,
  413. {
  414. json: true,
  415. open_timeout: 5,
  416. read_timeout: 14,
  417. user: Setting.get('es_user'),
  418. password: Setting.get('es_password'),
  419. }
  420. )
  421. Rails.logger.info "# #{response.code}"
  422. if !response.success?
  423. raise humanized_error(
  424. verb: 'GET',
  425. url: url,
  426. payload: data,
  427. response: response,
  428. )
  429. end
  430. Rails.logger.debug { response.data.to_json }
  431. if aggs_interval.blank? || aggs_interval[:interval].blank?
  432. ticket_ids = []
  433. response.data['hits']['hits'].each do |item|
  434. ticket_ids.push item['_id']
  435. end
  436. return {
  437. count: response.data['hits']['total'],
  438. ticket_ids: ticket_ids,
  439. }
  440. end
  441. response.data
  442. end
  443. def self.selector2query(selector, _current_user, aggs_interval, limit)
  444. query_must = []
  445. query_must_not = []
  446. relative_map = {
  447. day: 'd',
  448. year: 'y',
  449. month: 'M',
  450. hour: 'h',
  451. minute: 'm',
  452. }
  453. if selector.present?
  454. selector.each do |key, data|
  455. key_tmp = key.sub(/^.+?\./, '')
  456. t = {}
  457. # is/is not/contains/contains not
  458. if data['operator'] == 'is' || data['operator'] == 'is not' || data['operator'] == 'contains' || data['operator'] == 'contains not'
  459. if data['value'].class == Array
  460. t[:terms] = {}
  461. t[:terms][key_tmp] = data['value']
  462. else
  463. t[:term] = {}
  464. t[:term][key_tmp] = data['value']
  465. end
  466. if data['operator'] == 'is' || data['operator'] == 'contains'
  467. query_must.push t
  468. elsif data['operator'] == 'is not' || data['operator'] == 'contains not'
  469. query_must_not.push t
  470. end
  471. elsif data['operator'] == 'contains all' || data['operator'] == 'contains one' || data['operator'] == 'contains all not' || data['operator'] == 'contains one not'
  472. values = data['value'].split(',').map(&:strip)
  473. t[:query_string] = {}
  474. if data['operator'] == 'contains all'
  475. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  476. query_must.push t
  477. elsif data['operator'] == 'contains one not'
  478. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  479. query_must_not.push t
  480. elsif data['operator'] == 'contains one'
  481. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  482. query_must.push t
  483. elsif data['operator'] == 'contains all not'
  484. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  485. query_must_not.push t
  486. end
  487. # within last/within next (relative)
  488. elsif data['operator'] == 'within last (relative)' || data['operator'] == 'within next (relative)'
  489. range = relative_map[data['range'].to_sym]
  490. if range.blank?
  491. raise "Invalid relative_map for range '#{data['range']}'."
  492. end
  493. t[:range] = {}
  494. t[:range][key_tmp] = {}
  495. if data['operator'] == 'within last (relative)'
  496. t[:range][key_tmp][:gte] = "now-#{data['value']}#{range}"
  497. else
  498. t[:range][key_tmp][:lt] = "now+#{data['value']}#{range}"
  499. end
  500. query_must.push t
  501. # before/after (relative)
  502. elsif data['operator'] == 'before (relative)' || data['operator'] == 'after (relative)'
  503. range = relative_map[data['range'].to_sym]
  504. if range.blank?
  505. raise "Invalid relative_map for range '#{data['range']}'."
  506. end
  507. t[:range] = {}
  508. t[:range][key_tmp] = {}
  509. if data['operator'] == 'before (relative)'
  510. t[:range][key_tmp][:lt] = "now-#{data['value']}#{range}"
  511. else
  512. t[:range][key_tmp][:gt] = "now+#{data['value']}#{range}"
  513. end
  514. query_must.push t
  515. # before/after (absolute)
  516. elsif data['operator'] == 'before (absolute)' || data['operator'] == 'after (absolute)'
  517. t[:range] = {}
  518. t[:range][key_tmp] = {}
  519. if data['operator'] == 'before (absolute)'
  520. t[:range][key_tmp][:lt] = (data['value']).to_s
  521. else
  522. t[:range][key_tmp][:gt] = (data['value']).to_s
  523. end
  524. query_must.push t
  525. else
  526. raise "unknown operator '#{data['operator']}' for #{key}"
  527. end
  528. end
  529. end
  530. data = {
  531. query: {},
  532. size: limit,
  533. }
  534. # add aggs to filter
  535. if aggs_interval.present?
  536. if aggs_interval[:interval].present?
  537. data[:size] = 0
  538. data[:aggs] = {
  539. time_buckets: {
  540. date_histogram: {
  541. field: aggs_interval[:field],
  542. interval: aggs_interval[:interval],
  543. }
  544. }
  545. }
  546. end
  547. r = {}
  548. r[:range] = {}
  549. r[:range][aggs_interval[:field]] = {
  550. from: aggs_interval[:from],
  551. to: aggs_interval[:to],
  552. }
  553. query_must.push r
  554. end
  555. data[:query][:bool] ||= {}
  556. if query_must.present?
  557. data[:query][:bool][:must] = query_must
  558. end
  559. if query_must_not.present?
  560. data[:query][:bool][:must_not] = query_must_not
  561. end
  562. # add sort
  563. if aggs_interval.present? && aggs_interval[:field].present? && aggs_interval[:interval].blank?
  564. sort = []
  565. sort[0] = {}
  566. sort[0][aggs_interval[:field]] = {
  567. order: 'desc'
  568. }
  569. sort[1] = '_score'
  570. data['sort'] = sort
  571. end
  572. data
  573. end
  574. =begin
  575. return true if backend is configured
  576. result = SearchIndexBackend.enabled?
  577. =end
  578. def self.enabled?
  579. return false if Setting.get('es_url').blank?
  580. true
  581. end
  582. def self.build_url(type = nil, o_id = nil)
  583. return if !SearchIndexBackend.enabled?
  584. index = "#{Setting.get('es_index')}_#{Rails.env}"
  585. url = Setting.get('es_url')
  586. url = if type
  587. url_pipline = Setting.get('es_pipeline')
  588. if url_pipline.present?
  589. url_pipline = "?pipeline=#{url_pipline}"
  590. end
  591. if o_id
  592. "#{url}/#{index}/#{type}/#{o_id}#{url_pipline}"
  593. else
  594. "#{url}/#{index}/#{type}#{url_pipline}"
  595. end
  596. else
  597. "#{url}/#{index}"
  598. end
  599. url
  600. end
  601. def self.humanized_error(verb:, url:, payload: nil, response:)
  602. prefix = "Unable to process #{verb} request to elasticsearch URL '#{url}'."
  603. suffix = "\n\nResponse:\n#{response.inspect}\n\nPayload:\n#{payload.inspect}"
  604. if payload.respond_to?(:to_json)
  605. suffix += "\n\nPayload size: #{payload.to_json.bytesize / 1024 / 1024}M"
  606. end
  607. message = if response&.error&.match?('Connection refused')
  608. "Elasticsearch is not reachable, probably because it's not running or even installed."
  609. elsif url.end_with?('pipeline/zammad-attachment', 'pipeline=zammad-attachment') && response.code == 400
  610. 'The installed attachment plugin could not handle the request payload. Ensure that the correct attachment plugin is installed (5.6 => ingest-attachment, 2.4 - 5.5 => mapper-attachments).'
  611. else
  612. 'Check the response and payload for detailed information: '
  613. end
  614. result = "#{prefix} #{message}#{suffix}"
  615. Rails.logger.error result.first(40_000)
  616. result
  617. end
  618. # add * on simple query like "somephrase23" or "attribute: somephrase23"
  619. def self.append_wildcard_to_simple_query(query)
  620. query.strip!
  621. query += '*' if query.match?(/^([[:alnum:]._]+|[[:alnum:]]+\:\s*[[:alnum:]._]+)$/)
  622. query
  623. end
  624. end