search_index_backend.rb 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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. 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. version_supported = Gem::Version.new(installed_version) < Gem::Version.new('8')
  15. raise "Version #{installed_version} of configured elasticsearch is not supported." if !version_supported
  16. version_supported = Gem::Version.new(installed_version) > Gem::Version.new('2.3')
  17. raise "Version #{installed_version} of configured elasticsearch is not supported." if !version_supported
  18. return response.data
  19. end
  20. raise humanized_error(
  21. verb: 'GET',
  22. url: url,
  23. response: response,
  24. )
  25. end
  26. =begin
  27. update processors
  28. SearchIndexBackend.processors(
  29. _ingest/pipeline/attachment: {
  30. description: 'Extract attachment information from arrays',
  31. processors: [
  32. {
  33. foreach: {
  34. field: 'ticket.articles.attachments',
  35. processor: {
  36. attachment: {
  37. target_field: '_ingest._value.attachment',
  38. field: '_ingest._value.data'
  39. }
  40. }
  41. }
  42. }
  43. ]
  44. }
  45. )
  46. =end
  47. def self.processors(data)
  48. data.each do |key, items|
  49. url = "#{Setting.get('es_url')}/#{key}"
  50. items.each do |item|
  51. if item[:action] == 'delete'
  52. response = make_request(url, method: :delete)
  53. next if response.success?
  54. next if response.code.to_s == '404'
  55. raise humanized_error(
  56. verb: 'DELETE',
  57. url: url,
  58. response: response,
  59. )
  60. end
  61. item.delete(:action)
  62. make_request_and_validate(url, data: item, method: :put)
  63. end
  64. end
  65. true
  66. end
  67. =begin
  68. create/update/delete index
  69. SearchIndexBackend.index(
  70. :action => 'create', # create/update/delete
  71. :name => 'Ticket',
  72. :data => {
  73. :mappings => {
  74. :Ticket => {
  75. :properties => {
  76. :articles => {
  77. :type => 'nested',
  78. :properties => {
  79. 'attachment' => { :type => 'attachment' }
  80. }
  81. }
  82. }
  83. }
  84. }
  85. }
  86. )
  87. SearchIndexBackend.index(
  88. :action => 'delete', # create/update/delete
  89. :name => 'Ticket',
  90. )
  91. =end
  92. def self.index(data)
  93. url = build_url(type: data[:name], with_pipeline: false, with_document_type: false)
  94. return if url.blank?
  95. if data[:action] && data[:action] == 'delete'
  96. return SearchIndexBackend.remove(data[:name])
  97. end
  98. make_request_and_validate(url, data: data[:data], method: :put)
  99. end
  100. =begin
  101. add new object to search index
  102. SearchIndexBackend.add('Ticket', some_data_object)
  103. =end
  104. def self.add(type, data)
  105. url = build_url(type: type, object_id: data['id'])
  106. return if url.blank?
  107. make_request_and_validate(url, data: data, method: :post)
  108. end
  109. =begin
  110. This function updates specifc attributes of an index based on a query.
  111. data = {
  112. organization: {
  113. name: "Zammad Foundation"
  114. }
  115. }
  116. where = {
  117. organization_id: 1
  118. }
  119. SearchIndexBackend.update_by_query('Ticket', data, where)
  120. =end
  121. def self.update_by_query(type, data, where)
  122. return if data.blank?
  123. return if where.blank?
  124. url = build_url(type: type, action: '_update_by_query', with_pipeline: false, with_document_type: false, url_params: { conflicts: 'proceed' })
  125. return if url.blank?
  126. script_list = []
  127. data.each do |key, _value|
  128. script_list.push("ctx._source.#{key}=params.#{key}")
  129. end
  130. data = {
  131. script: {
  132. lang: 'painless',
  133. source: script_list.join(';'),
  134. params: data,
  135. },
  136. query: {
  137. term: where,
  138. },
  139. }
  140. make_request_and_validate(url, data: data, method: :post, read_timeout: 10.minutes)
  141. end
  142. =begin
  143. remove whole data from index
  144. SearchIndexBackend.remove('Ticket', 123)
  145. SearchIndexBackend.remove('Ticket')
  146. =end
  147. def self.remove(type, o_id = nil)
  148. url = if o_id
  149. build_url(type: type, object_id: o_id, with_pipeline: false, with_document_type: true)
  150. else
  151. build_url(type: type, object_id: o_id, with_pipeline: false, with_document_type: false)
  152. end
  153. return if url.blank?
  154. response = make_request(url, method: :delete)
  155. return true if response.success?
  156. return true if response.code.to_s == '400'
  157. humanized_error = humanized_error(
  158. verb: 'DELETE',
  159. url: url,
  160. response: response,
  161. )
  162. Rails.logger.warn "Can't delete index: #{humanized_error}"
  163. false
  164. end
  165. =begin
  166. @param query [String] search query
  167. @param index [String, Array<String>] indexes to search in (see search_by_index)
  168. @param options [Hash] search options (see build_query)
  169. @return search result
  170. @example Sample queries
  171. result = SearchIndexBackend.search('search query', ['User', 'Organization'], limit: limit)
  172. - result = SearchIndexBackend.search('search query', 'User', limit: limit)
  173. result = SearchIndexBackend.search('search query', 'User', limit: limit, sort_by: ['updated_at'], order_by: ['desc'])
  174. result = SearchIndexBackend.search('search query', 'User', limit: limit, sort_by: ['active', updated_at'], order_by: ['desc', 'desc'])
  175. result = [
  176. {
  177. :id => 123,
  178. :type => 'User',
  179. },
  180. {
  181. :id => 125,
  182. :type => 'User',
  183. },
  184. {
  185. :id => 15,
  186. :type => 'Organization',
  187. }
  188. ]
  189. =end
  190. def self.search(query, index, options = {})
  191. if !index.is_a? Array
  192. return search_by_index(query, index, options)
  193. end
  194. index
  195. .map { |local_index| search_by_index(query, local_index, options) }
  196. .compact
  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. 'default_operator' => 'AND',
  214. 'analyze_wildcard' => true,
  215. }
  216. }
  217. if (fields = options.dig(:highlight_fields_by_indexes, index.to_sym))
  218. condition['query_string']['fields'] = fields
  219. end
  220. query_data = build_query(condition, options)
  221. if (fields = options.dig(:highlight_fields_by_indexes, index.to_sym))
  222. fields_for_highlight = fields.each_with_object({}) { |elem, memo| memo[elem] = {} }
  223. query_data[:highlight] = { fields: fields_for_highlight }
  224. end
  225. response = make_request(url, data: query_data)
  226. if !response.success?
  227. Rails.logger.error humanized_error(
  228. verb: 'GET',
  229. url: url,
  230. payload: query_data,
  231. response: response,
  232. )
  233. return []
  234. end
  235. data = response.data&.dig('hits', 'hits')
  236. return [] if !data
  237. data.map do |item|
  238. Rails.logger.info "... #{item['_type']} #{item['_id']}"
  239. output = {
  240. id: item['_id'],
  241. type: index,
  242. }
  243. if options.dig(:highlight_fields_by_indexes, index.to_sym)
  244. output[:highlight] = item['highlight']
  245. end
  246. output
  247. end
  248. end
  249. def self.search_by_index_sort(sort_by = nil, order_by = nil)
  250. result = []
  251. sort_by&.each_with_index do |value, index|
  252. next if value.blank?
  253. next if order_by&.at(index).blank?
  254. # for sorting values use .keyword values (no analyzer is used - plain values)
  255. if value !~ /\./ && value !~ /_(time|date|till|id|ids|at)$/
  256. value += '.keyword'
  257. end
  258. result.push(
  259. value => {
  260. order: order_by[index],
  261. },
  262. )
  263. end
  264. if result.blank?
  265. result.push(
  266. updated_at: {
  267. order: 'desc',
  268. },
  269. )
  270. end
  271. result.push('_score')
  272. result
  273. end
  274. =begin
  275. get count of tickets and tickets which match on selector
  276. result = SearchIndexBackend.selectors(index, selector)
  277. example with a simple search:
  278. result = SearchIndexBackend.selectors('Ticket', { 'category' => { 'operator' => 'is', 'value' => 'aa::ab' } })
  279. result = [
  280. { id: 1, type: 'Ticket' },
  281. { id: 2, type: 'Ticket' },
  282. { id: 3, type: 'Ticket' },
  283. ]
  284. you also can get aggregations
  285. result = SearchIndexBackend.selectors(index, selector, options, aggs_interval)
  286. example for aggregations within one year
  287. aggs_interval = {
  288. from: '2015-01-01',
  289. to: '2015-12-31',
  290. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  291. field: 'created_at',
  292. }
  293. options = {
  294. limit: 123,
  295. current_user: User.find(123),
  296. }
  297. result = SearchIndexBackend.selectors('Ticket', { 'category' => { 'operator' => 'is', 'value' => 'aa::ab' } }, options, aggs_interval)
  298. result = {
  299. hits:{
  300. total:4819,
  301. },
  302. aggregations:{
  303. time_buckets:{
  304. buckets:[
  305. {
  306. key_as_string:"2014-10-01T00:00:00.000Z",
  307. key:1412121600000,
  308. doc_count:420
  309. },
  310. {
  311. key_as_string:"2014-11-01T00:00:00.000Z",
  312. key:1414800000000,
  313. doc_count:561
  314. },
  315. ...
  316. ]
  317. }
  318. }
  319. }
  320. =end
  321. def self.selectors(index, selectors = nil, options = {}, aggs_interval = nil)
  322. raise 'no selectors given' if !selectors
  323. url = build_url(type: index, action: '_search', with_pipeline: false, with_document_type: true)
  324. return if url.blank?
  325. data = selector2query(selectors, options, aggs_interval)
  326. response = make_request(url, data: data)
  327. if !response.success?
  328. raise humanized_error(
  329. verb: 'GET',
  330. url: url,
  331. payload: data,
  332. response: response,
  333. )
  334. end
  335. Rails.logger.debug { response.data.to_json }
  336. if aggs_interval.blank? || aggs_interval[:interval].blank?
  337. ticket_ids = []
  338. response.data['hits']['hits'].each do |item|
  339. ticket_ids.push item['_id']
  340. end
  341. # in lower ES 6 versions, we get total count directly, in higher
  342. # versions we need to pick it from total has
  343. count = response.data['hits']['total']
  344. if response.data['hits']['total'].class != Integer
  345. count = response.data['hits']['total']['value']
  346. end
  347. return {
  348. count: count,
  349. ticket_ids: ticket_ids,
  350. }
  351. end
  352. response.data
  353. end
  354. DEFAULT_SELECTOR_OPTIONS = {
  355. limit: 10
  356. }.freeze
  357. def self.selector2query(selector, options, aggs_interval)
  358. options = DEFAULT_QUERY_OPTIONS.merge(options.deep_symbolize_keys)
  359. current_user = options[:current_user]
  360. current_user_id = UserInfo.current_user_id
  361. if current_user
  362. current_user_id = current_user.id
  363. end
  364. query_must = []
  365. query_must_not = []
  366. relative_map = {
  367. day: 'd',
  368. year: 'y',
  369. month: 'M',
  370. hour: 'h',
  371. minute: 'm',
  372. }
  373. if selector.present?
  374. selector.each do |key, data|
  375. key_tmp = key.sub(/^.+?\./, '')
  376. wildcard_or_term = 'term'
  377. if data['value'].is_a?(Array)
  378. wildcard_or_term = 'terms'
  379. end
  380. t = {}
  381. # use .keyword in case of compare exact values
  382. if data['operator'] == 'is' || data['operator'] == 'is not'
  383. case data['pre_condition']
  384. when 'not_set'
  385. data['value'] = if key_tmp.match?(/^(created_by|updated_by|owner|customer|user)_id/)
  386. 1
  387. else
  388. 'NULL'
  389. end
  390. when 'current_user.id'
  391. raise "Use current_user.id in selector, but no current_user is set #{data.inspect}" if !current_user_id
  392. data['value'] = []
  393. wildcard_or_term = 'terms'
  394. if key_tmp == 'out_of_office_replacement_id'
  395. data['value'].push User.find(current_user_id).out_of_office_agent_of.pluck(:id)
  396. else
  397. data['value'].push current_user_id
  398. end
  399. when 'current_user.organization_id'
  400. raise "Use current_user.id in selector, but no current_user is set #{data.inspect}" if !current_user_id
  401. user = User.find_by(id: current_user_id)
  402. data['value'] = user.organization_id
  403. end
  404. if data['value'].is_a?(Array)
  405. data['value'].each do |value|
  406. next if !value.is_a?(String) || value !~ /[A-z]/
  407. key_tmp += '.keyword'
  408. break
  409. end
  410. elsif data['value'].is_a?(String) && /[A-z]/.match?(data['value'])
  411. key_tmp += '.keyword'
  412. end
  413. end
  414. # use .keyword and wildcard search in cases where query contains non A-z chars
  415. if data['operator'] == 'contains' || data['operator'] == 'contains not'
  416. if data['value'].is_a?(Array)
  417. data['value'].each_with_index do |value, index|
  418. next if !value.is_a?(String) || value !~ /[A-z]/ || value !~ /\W/
  419. data['value'][index] = "*#{value}*"
  420. key_tmp += '.keyword'
  421. wildcard_or_term = 'wildcards'
  422. break
  423. end
  424. elsif data['value'].is_a?(String) && /[A-z]/.match?(data['value']) && data['value'] =~ /\W/
  425. data['value'] = "*#{data['value']}*"
  426. key_tmp += '.keyword'
  427. wildcard_or_term = 'wildcard'
  428. end
  429. end
  430. # is/is not/contains/contains not
  431. case data['operator']
  432. when 'is', 'is not', 'contains', 'contains not'
  433. t[wildcard_or_term] = {}
  434. t[wildcard_or_term][key_tmp] = data['value']
  435. case data['operator']
  436. when 'is', 'contains'
  437. query_must.push t
  438. when 'is not', 'contains not'
  439. query_must_not.push t
  440. end
  441. when 'contains all', 'contains one', 'contains all not', 'contains one not'
  442. values = data['value'].split(',').map(&:strip)
  443. t[:query_string] = {}
  444. case data['operator']
  445. when 'contains all'
  446. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  447. query_must.push t
  448. when 'contains one not'
  449. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  450. query_must_not.push t
  451. when 'contains one'
  452. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" OR "')}\""
  453. query_must.push t
  454. when 'contains all not'
  455. t[:query_string][:query] = "#{key_tmp}:\"#{values.join('" AND "')}\""
  456. query_must_not.push t
  457. end
  458. # within last/within next (relative)
  459. when 'within last (relative)', 'within next (relative)'
  460. range = relative_map[data['range'].to_sym]
  461. if range.blank?
  462. raise "Invalid relative_map for range '#{data['range']}'."
  463. end
  464. t[:range] = {}
  465. t[:range][key_tmp] = {}
  466. if data['operator'] == 'within last (relative)'
  467. t[:range][key_tmp][:gte] = "now-#{data['value']}#{range}"
  468. else
  469. t[:range][key_tmp][:lt] = "now+#{data['value']}#{range}"
  470. end
  471. query_must.push t
  472. # before/after (relative)
  473. when 'before (relative)', 'after (relative)'
  474. range = relative_map[data['range'].to_sym]
  475. if range.blank?
  476. raise "Invalid relative_map for range '#{data['range']}'."
  477. end
  478. t[:range] = {}
  479. t[:range][key_tmp] = {}
  480. if data['operator'] == 'before (relative)'
  481. t[:range][key_tmp][:lt] = "now-#{data['value']}#{range}"
  482. else
  483. t[:range][key_tmp][:gt] = "now+#{data['value']}#{range}"
  484. end
  485. query_must.push t
  486. # before/after (absolute)
  487. when 'before (absolute)', 'after (absolute)'
  488. t[:range] = {}
  489. t[:range][key_tmp] = {}
  490. if data['operator'] == 'before (absolute)'
  491. t[:range][key_tmp][:lt] = (data['value'])
  492. else
  493. t[:range][key_tmp][:gt] = (data['value'])
  494. end
  495. query_must.push t
  496. else
  497. raise "unknown operator '#{data['operator']}' for #{key}"
  498. end
  499. end
  500. end
  501. data = {
  502. query: {},
  503. size: options[:limit],
  504. }
  505. # add aggs to filter
  506. if aggs_interval.present?
  507. if aggs_interval[:interval].present?
  508. data[:size] = 0
  509. data[:aggs] = {
  510. time_buckets: {
  511. date_histogram: {
  512. field: aggs_interval[:field],
  513. interval: aggs_interval[:interval],
  514. }
  515. }
  516. }
  517. if aggs_interval[:timezone].present?
  518. data[:aggs][:time_buckets][:date_histogram][:time_zone] = aggs_interval[:timezone]
  519. end
  520. end
  521. r = {}
  522. r[:range] = {}
  523. r[:range][aggs_interval[:field]] = {
  524. from: aggs_interval[:from],
  525. to: aggs_interval[:to],
  526. }
  527. query_must.push r
  528. end
  529. data[:query][:bool] ||= {}
  530. if query_must.present?
  531. data[:query][:bool][:must] = query_must
  532. end
  533. if query_must_not.present?
  534. data[:query][:bool][:must_not] = query_must_not
  535. end
  536. # add sort
  537. if aggs_interval.present? && aggs_interval[:field].present? && aggs_interval[:interval].blank?
  538. sort = []
  539. sort[0] = {}
  540. sort[0][aggs_interval[:field]] = {
  541. order: 'desc'
  542. }
  543. sort[1] = '_score'
  544. data['sort'] = sort
  545. else
  546. data['sort'] = search_by_index_sort(options[:sort_by], options[:order_by])
  547. end
  548. data
  549. end
  550. =begin
  551. return true if backend is configured
  552. result = SearchIndexBackend.enabled?
  553. =end
  554. def self.enabled?
  555. return false if Setting.get('es_url').blank?
  556. true
  557. end
  558. def self.build_index_name(index = nil)
  559. local_index = "#{Setting.get('es_index')}_#{Rails.env}"
  560. return local_index if index.blank?
  561. return "#{local_index}/#{index}" if lower_equal_es56?
  562. "#{local_index}_#{index.underscore.tr('/', '_')}"
  563. end
  564. =begin
  565. return true if the elastic search version is lower equal 5.6
  566. result = SearchIndexBackend.lower_equal_es56?
  567. returns
  568. result = true
  569. =end
  570. def self.lower_equal_es56?
  571. Setting.get('es_multi_index') == false
  572. end
  573. =begin
  574. generate url for index or document access (only for internal use)
  575. # url to access single document in index (in case with_pipeline or not)
  576. url = SearchIndexBackend.build_url(type: 'User', object_id: 123, with_pipeline: true)
  577. # url to access whole index
  578. url = SearchIndexBackend.build_url(type: 'User')
  579. # url to access document definition in index (only es6 and higher)
  580. url = SearchIndexBackend.build_url(type: 'User', with_pipeline: false, with_document_type: true)
  581. # base url
  582. url = SearchIndexBackend.build_url
  583. =end
  584. # rubocop:disable Metrics/ParameterLists
  585. def self.build_url(type: nil, action: nil, object_id: nil, with_pipeline: true, with_document_type: true, url_params: {})
  586. # rubocop:enable Metrics/ParameterLists
  587. return if !SearchIndexBackend.enabled?
  588. # set index
  589. index = build_index_name(type)
  590. # add pipeline if needed
  591. if index && with_pipeline == true
  592. url_pipline = Setting.get('es_pipeline')
  593. if url_pipline.present?
  594. url_params['pipeline'] = url_pipline
  595. end
  596. end
  597. # prepare url params
  598. params_string = ''
  599. if url_params.present?
  600. params_string = "?#{URI.encode_www_form(url_params)}"
  601. end
  602. url = Setting.get('es_url')
  603. return "#{url}#{params_string}" if index.blank?
  604. # add type information
  605. url = "#{url}/#{index}"
  606. # add document type
  607. if with_document_type && !lower_equal_es56?
  608. url = "#{url}/_doc"
  609. end
  610. # add action
  611. if action
  612. url = "#{url}/#{action}"
  613. end
  614. # add object id
  615. if object_id.present?
  616. url = "#{url}/#{object_id}"
  617. end
  618. "#{url}#{params_string}"
  619. end
  620. def self.humanized_error(verb:, url:, response:, payload: nil)
  621. prefix = "Unable to process #{verb} request to elasticsearch URL '#{url}'."
  622. suffix = "\n\nResponse:\n#{response.inspect}\n\n"
  623. if payload.respond_to?(:to_json)
  624. suffix += "Payload:\n#{payload.to_json}"
  625. suffix += "\n\nPayload size: #{payload.to_json.bytesize / 1024 / 1024}M"
  626. else
  627. suffix += "Payload:\n#{payload.inspect}"
  628. end
  629. message = if response&.error&.match?('Connection refused')
  630. "Elasticsearch is not reachable, probably because it's not running or even installed."
  631. elsif url.end_with?('pipeline/zammad-attachment', 'pipeline=zammad-attachment') && response.code == 400
  632. '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).'
  633. else
  634. 'Check the response and payload for detailed information: '
  635. end
  636. result = "#{prefix} #{message}#{suffix}"
  637. Rails.logger.error result.first(40_000)
  638. result
  639. end
  640. # add * on simple query like "somephrase23"
  641. def self.append_wildcard_to_simple_query(query)
  642. query.strip!
  643. query += '*' if query.exclude?(':')
  644. query
  645. end
  646. =begin
  647. @param condition [Hash] search condition
  648. @param options [Hash] search options
  649. @option options [Integer] :from
  650. @option options [Integer] :limit
  651. @option options [Hash] :query_extension applied to ElasticSearch query
  652. @option options [Array<String>] :order_by ordering directions, desc or asc
  653. @option options [Array<String>] :sort_by fields to sort by
  654. =end
  655. DEFAULT_QUERY_OPTIONS = {
  656. from: 0,
  657. limit: 10
  658. }.freeze
  659. def self.build_query(condition, options = {})
  660. options = DEFAULT_QUERY_OPTIONS.merge(options.deep_symbolize_keys)
  661. data = {
  662. from: options[:from],
  663. size: options[:limit],
  664. sort: search_by_index_sort(options[:sort_by], options[:order_by]),
  665. query: {
  666. bool: {
  667. must: []
  668. }
  669. }
  670. }
  671. if (extension = options[:query_extension])
  672. data[:query].deep_merge! extension.deep_dup
  673. end
  674. data[:query][:bool][:must].push condition
  675. data
  676. end
  677. =begin
  678. refreshes all indexes to make previous request data visible in future requests
  679. SearchIndexBackend.refresh
  680. =end
  681. def self.refresh
  682. return if !enabled?
  683. url = "#{Setting.get('es_url')}/_all/_refresh"
  684. make_request_and_validate(url, method: :post)
  685. end
  686. =begin
  687. helper method for making HTTP calls
  688. @param url [String] url
  689. @option params [Hash] :data is a payload hash
  690. @option params [Symbol] :method is a HTTP method
  691. @option params [Integer] :open_timeout is HTTP request open timeout
  692. @option params [Integer] :read_timeout is HTTP request read timeout
  693. @return UserAgent response
  694. =end
  695. def self.make_request(url, data: {}, method: :get, open_timeout: 8, read_timeout: 180)
  696. Rails.logger.info "# curl -X #{method} \"#{url}\" "
  697. Rails.logger.debug { "-d '#{data.to_json}'" } if data.present?
  698. options = {
  699. json: true,
  700. open_timeout: open_timeout,
  701. read_timeout: read_timeout,
  702. total_timeout: (open_timeout + read_timeout + 60),
  703. open_socket_tries: 3,
  704. user: Setting.get('es_user'),
  705. password: Setting.get('es_password'),
  706. }
  707. response = UserAgent.send(method, url, data, options)
  708. Rails.logger.info "# #{response.code}"
  709. response
  710. end
  711. =begin
  712. helper method for making HTTP calls and raising error if response was not success
  713. @param url [String] url
  714. @option args [Hash] see {make_request}
  715. @return [Boolean] always returns true. Raises error if something went wrong.
  716. =end
  717. def self.make_request_and_validate(url, **args)
  718. response = make_request(url, args)
  719. return true if response.success?
  720. raise humanized_error(
  721. verb: args[:method],
  722. url: url,
  723. payload: args[:data],
  724. response: response
  725. )
  726. end
  727. end