search_index_backend.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. 'analyze_wildcard' => true,
  289. }
  290. }
  291. data['query']['bool']['must'].push condition
  292. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  293. Rails.logger.debug { " -d'#{data.to_json}'" }
  294. response = UserAgent.get(
  295. url,
  296. data,
  297. {
  298. json: true,
  299. open_timeout: 5,
  300. read_timeout: 14,
  301. user: Setting.get('es_user'),
  302. password: Setting.get('es_password'),
  303. }
  304. )
  305. Rails.logger.info "# #{response.code}"
  306. if !response.success?
  307. Rails.logger.error humanized_error(
  308. verb: 'GET',
  309. url: url,
  310. payload: data,
  311. response: response,
  312. )
  313. return []
  314. end
  315. data = response.data
  316. ids = []
  317. return ids if !data
  318. return ids if !data['hits']
  319. return ids if !data['hits']['hits']
  320. data['hits']['hits'].each do |item|
  321. Rails.logger.info "... #{item['_type']} #{item['_id']}"
  322. data = {
  323. id: item['_id'],
  324. type: item['_type'],
  325. }
  326. ids.push data
  327. end
  328. ids
  329. end
  330. def self.search_by_index_sort(sort_by = [], order_by = [])
  331. result = []
  332. sort_by.each_with_index do |value, index|
  333. next if value.blank?
  334. next if order_by[index].blank?
  335. if value !~ /\./ && value !~ /_(time|date|till|id|ids|at)$/
  336. value += '.raw'
  337. end
  338. result.push(
  339. value => {
  340. order: order_by[index],
  341. },
  342. )
  343. end
  344. if result.blank?
  345. result.push(
  346. updated_at: {
  347. order: 'desc',
  348. },
  349. )
  350. end
  351. # add sorting by active if active is not part of the query
  352. if result.flat_map(&:keys).exclude?(:active)
  353. result.unshift(
  354. active: {
  355. order: 'desc',
  356. },
  357. )
  358. end
  359. result.push('_score')
  360. result
  361. end
  362. =begin
  363. get count of tickets and tickets which match on selector
  364. aggs_interval = {
  365. from: '2015-01-01',
  366. to: '2015-12-31',
  367. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  368. field: 'created_at',
  369. }
  370. result = SearchIndexBackend.selectors(index, params[:condition], limit, current_user, aggs_interval)
  371. # for aggregations
  372. result = {
  373. hits:{
  374. total:4819,
  375. },
  376. aggregations:{
  377. time_buckets:{
  378. buckets:[
  379. {
  380. key_as_string:"2014-10-01T00:00:00.000Z",
  381. key:1412121600000,
  382. doc_count:420
  383. },
  384. {
  385. key_as_string:"2014-11-01T00:00:00.000Z",
  386. key:1414800000000,
  387. doc_count:561
  388. },
  389. ...
  390. ]
  391. }
  392. }
  393. }
  394. =end
  395. def self.selectors(index = nil, selectors = nil, limit = 10, current_user = nil, aggs_interval = nil)
  396. raise 'no selectors given' if !selectors
  397. url = build_url
  398. return if url.blank?
  399. url += if index
  400. if index.class == Array
  401. "/#{index.join(',')}/_search"
  402. else
  403. "/#{index}/_search"
  404. end
  405. else
  406. '/_search'
  407. end
  408. data = selector2query(selectors, current_user, aggs_interval, limit)
  409. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  410. Rails.logger.debug { " -d'#{data.to_json}'" }
  411. response = UserAgent.get(
  412. url,
  413. data,
  414. {
  415. json: true,
  416. open_timeout: 5,
  417. read_timeout: 14,
  418. user: Setting.get('es_user'),
  419. password: Setting.get('es_password'),
  420. }
  421. )
  422. Rails.logger.info "# #{response.code}"
  423. if !response.success?
  424. raise humanized_error(
  425. verb: 'GET',
  426. url: url,
  427. payload: data,
  428. response: response,
  429. )
  430. end
  431. Rails.logger.debug { response.data.to_json }
  432. if aggs_interval.blank? || aggs_interval[:interval].blank?
  433. ticket_ids = []
  434. response.data['hits']['hits'].each do |item|
  435. ticket_ids.push item['_id']
  436. end
  437. return {
  438. count: response.data['hits']['total'],
  439. ticket_ids: ticket_ids,
  440. }
  441. end
  442. response.data
  443. end
  444. def self.selector2query(selector, _current_user, aggs_interval, limit)
  445. query_must = []
  446. query_must_not = []
  447. relative_map = {
  448. day: 'd',
  449. year: 'y',
  450. month: 'M',
  451. hour: 'h',
  452. minute: 'm',
  453. }
  454. if selector.present?
  455. selector.each do |key, data|
  456. key_tmp = key.sub(/^.+?\./, '')
  457. t = {}
  458. # is/is not/contains/contains not
  459. if data['operator'] == 'is' || data['operator'] == 'is not' || data['operator'] == 'contains' || data['operator'] == 'contains not'
  460. if data['value'].class == Array
  461. t[:terms] = {}
  462. t[:terms][key_tmp] = data['value']
  463. else
  464. t[:term] = {}
  465. t[:term][key_tmp] = data['value']
  466. end
  467. if data['operator'] == 'is' || data['operator'] == 'contains'
  468. query_must.push t
  469. elsif data['operator'] == 'is not' || data['operator'] == 'contains not'
  470. query_must_not.push t
  471. end
  472. elsif data['operator'] == 'contains all' || data['operator'] == 'contains one' || data['operator'] == 'contains all not' || data['operator'] == 'contains one not'
  473. values = data['value'].split(',').map(&:strip)
  474. t[:query_string] = {}
  475. if data['operator'] == 'contains all'
  476. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  477. query_must.push t
  478. elsif data['operator'] == 'contains one not'
  479. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  480. query_must_not.push t
  481. elsif data['operator'] == 'contains one'
  482. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  483. query_must.push t
  484. elsif data['operator'] == 'contains all not'
  485. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  486. query_must_not.push t
  487. end
  488. # within last/within next (relative)
  489. elsif data['operator'] == 'within last (relative)' || data['operator'] == 'within next (relative)'
  490. range = relative_map[data['range'].to_sym]
  491. if range.blank?
  492. raise "Invalid relative_map for range '#{data['range']}'."
  493. end
  494. t[:range] = {}
  495. t[:range][key_tmp] = {}
  496. if data['operator'] == 'within last (relative)'
  497. t[:range][key_tmp][:gte] = "now-#{data['value']}#{range}"
  498. else
  499. t[:range][key_tmp][:lt] = "now+#{data['value']}#{range}"
  500. end
  501. query_must.push t
  502. # before/after (relative)
  503. elsif data['operator'] == 'before (relative)' || data['operator'] == 'after (relative)'
  504. range = relative_map[data['range'].to_sym]
  505. if range.blank?
  506. raise "Invalid relative_map for range '#{data['range']}'."
  507. end
  508. t[:range] = {}
  509. t[:range][key_tmp] = {}
  510. if data['operator'] == 'before (relative)'
  511. t[:range][key_tmp][:lt] = "now-#{data['value']}#{range}"
  512. else
  513. t[:range][key_tmp][:gt] = "now+#{data['value']}#{range}"
  514. end
  515. query_must.push t
  516. # before/after (absolute)
  517. elsif data['operator'] == 'before (absolute)' || data['operator'] == 'after (absolute)'
  518. t[:range] = {}
  519. t[:range][key_tmp] = {}
  520. if data['operator'] == 'before (absolute)'
  521. t[:range][key_tmp][:lt] = (data['value']).to_s
  522. else
  523. t[:range][key_tmp][:gt] = (data['value']).to_s
  524. end
  525. query_must.push t
  526. else
  527. raise "unknown operator '#{data['operator']}' for #{key}"
  528. end
  529. end
  530. end
  531. data = {
  532. query: {},
  533. size: limit,
  534. }
  535. # add aggs to filter
  536. if aggs_interval.present?
  537. if aggs_interval[:interval].present?
  538. data[:size] = 0
  539. data[:aggs] = {
  540. time_buckets: {
  541. date_histogram: {
  542. field: aggs_interval[:field],
  543. interval: aggs_interval[:interval],
  544. }
  545. }
  546. }
  547. end
  548. r = {}
  549. r[:range] = {}
  550. r[:range][aggs_interval[:field]] = {
  551. from: aggs_interval[:from],
  552. to: aggs_interval[:to],
  553. }
  554. query_must.push r
  555. end
  556. data[:query][:bool] ||= {}
  557. if query_must.present?
  558. data[:query][:bool][:must] = query_must
  559. end
  560. if query_must_not.present?
  561. data[:query][:bool][:must_not] = query_must_not
  562. end
  563. # add sort
  564. if aggs_interval.present? && aggs_interval[:field].present? && aggs_interval[:interval].blank?
  565. sort = []
  566. sort[0] = {}
  567. sort[0][aggs_interval[:field]] = {
  568. order: 'desc'
  569. }
  570. sort[1] = '_score'
  571. data['sort'] = sort
  572. end
  573. data
  574. end
  575. =begin
  576. return true if backend is configured
  577. result = SearchIndexBackend.enabled?
  578. =end
  579. def self.enabled?
  580. return false if Setting.get('es_url').blank?
  581. true
  582. end
  583. def self.build_url(type = nil, o_id = nil)
  584. return if !SearchIndexBackend.enabled?
  585. index = "#{Setting.get('es_index')}_#{Rails.env}"
  586. url = Setting.get('es_url')
  587. url = if type
  588. url_pipline = Setting.get('es_pipeline')
  589. if url_pipline.present?
  590. url_pipline = "?pipeline=#{url_pipline}"
  591. end
  592. if o_id
  593. "#{url}/#{index}/#{type}/#{o_id}#{url_pipline}"
  594. else
  595. "#{url}/#{index}/#{type}#{url_pipline}"
  596. end
  597. else
  598. "#{url}/#{index}"
  599. end
  600. url
  601. end
  602. def self.humanized_error(verb:, url:, payload: nil, response:)
  603. prefix = "Unable to process #{verb} request to elasticsearch URL '#{url}'."
  604. suffix = "\n\nResponse:\n#{response.inspect}\n\nPayload:\n#{payload.inspect}"
  605. if payload.respond_to?(:to_json)
  606. suffix += "\n\nPayload size: #{payload.to_json.bytesize / 1024 / 1024}M"
  607. end
  608. message = if response&.error&.match?('Connection refused')
  609. "Elasticsearch is not reachable, probably because it's not running or even installed."
  610. elsif url.end_with?('pipeline/zammad-attachment', 'pipeline=zammad-attachment') && response.code == 400
  611. '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).'
  612. else
  613. 'Check the response and payload for detailed information: '
  614. end
  615. result = "#{prefix} #{message}#{suffix}"
  616. Rails.logger.error result.first(40_000)
  617. result
  618. end
  619. # add * on simple query like "somephrase23"
  620. def self.append_wildcard_to_simple_query(query)
  621. query.strip!
  622. query += '*' if !query.match?(/:/)
  623. query
  624. end
  625. end