search_index_backend.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class SearchIndexBackend
  3. =begin
  4. create/update/delete index
  5. SearchIndexBackend.index(
  6. :action => 'create', # create/update/delete
  7. :data => {
  8. :mappings => {
  9. :Ticket => {
  10. :properties => {
  11. :articles => {
  12. :type => 'nested',
  13. :properties => {
  14. 'attachment' => { :type => 'attachment' }
  15. }
  16. }
  17. }
  18. }
  19. }
  20. }
  21. )
  22. SearchIndexBackend.index(
  23. :action => 'delete', # create/update/delete
  24. :name => 'Ticket', # optional
  25. )
  26. SearchIndexBackend.index(
  27. :action => 'delete', # create/update/delete
  28. )
  29. =end
  30. def self.index(data)
  31. url = build_url(data[:name])
  32. return if !url
  33. if data[:action] && data[:action] == 'delete'
  34. return SearchIndexBackend.remove(data[:name])
  35. end
  36. Rails.logger.info "# curl -X PUT \"#{url}\" \\"
  37. Rails.logger.debug "-d '#{data[:data].to_json}'"
  38. response = UserAgent.put(
  39. url,
  40. data[:data],
  41. {
  42. json: true,
  43. open_timeout: 5,
  44. read_timeout: 20,
  45. user: Setting.get('es_user'),
  46. password: Setting.get('es_password'),
  47. }
  48. )
  49. Rails.logger.info "# #{response.code}"
  50. return true if response.success?
  51. raise "Unable to process PUT at #{url}\n#{response.inspect}"
  52. end
  53. =begin
  54. add new object to search index
  55. SearchIndexBackend.add('Ticket', some_data_object)
  56. =end
  57. def self.add(type, data)
  58. url = build_url(type, data['id'])
  59. return if !url
  60. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  61. Rails.logger.debug "-d '#{data.to_json}'"
  62. response = UserAgent.post(
  63. url,
  64. data,
  65. {
  66. json: true,
  67. open_timeout: 5,
  68. read_timeout: 20,
  69. user: Setting.get('es_user'),
  70. password: Setting.get('es_password'),
  71. }
  72. )
  73. Rails.logger.info "# #{response.code}"
  74. return true if response.success?
  75. raise "Unable to process POST at #{url} (size: #{data.to_json.bytesize / 1024 / 1024}M)\n#{response.inspect}"
  76. end
  77. =begin
  78. remove whole data from index
  79. SearchIndexBackend.remove('Ticket', 123)
  80. SearchIndexBackend.remove('Ticket')
  81. =end
  82. def self.remove(type, o_id = nil)
  83. url = build_url(type, o_id)
  84. return if !url
  85. Rails.logger.info "# curl -X DELETE \"#{url}\""
  86. response = UserAgent.delete(
  87. url,
  88. {
  89. open_timeout: 5,
  90. read_timeout: 14,
  91. user: Setting.get('es_user'),
  92. password: Setting.get('es_password'),
  93. }
  94. )
  95. Rails.logger.info "# #{response.code}"
  96. return true if response.success?
  97. #Rails.logger.info "NOTICE: can't delete index #{url}: " + response.inspect
  98. false
  99. end
  100. =begin
  101. return search result
  102. result = SearchIndexBackend.search('search query', limit, ['User', 'Organization'])
  103. result = SearchIndexBackend.search('search query', limit, 'User')
  104. result = [
  105. {
  106. :id => 123,
  107. :type => 'User',
  108. },
  109. {
  110. :id => 125,
  111. :type => 'User',
  112. },
  113. {
  114. :id => 15,
  115. :type => 'Organization',
  116. }
  117. ]
  118. =end
  119. def self.search(query, limit = 10, index = nil, query_extention = {})
  120. return [] if !query
  121. if index.class == Array
  122. ids = []
  123. index.each do |local_index|
  124. local_ids = search_by_index(query, limit, local_index, query_extention)
  125. ids = ids.concat(local_ids)
  126. end
  127. return ids
  128. end
  129. search_by_index(query, limit, index, query_extention)
  130. end
  131. def self.search_by_index(query, limit = 10, index = nil, query_extention = {})
  132. return [] if !query
  133. url = build_url()
  134. return if !url
  135. url += if index
  136. if index.class == Array
  137. "/#{index.join(',')}/_search"
  138. else
  139. "/#{index}/_search"
  140. end
  141. else
  142. '/_search'
  143. end
  144. data = {}
  145. data['from'] = 0
  146. data['size'] = limit
  147. data['sort'] =
  148. [
  149. {
  150. updated_at: {
  151. order: 'desc'
  152. }
  153. },
  154. '_score'
  155. ]
  156. data['query'] = query_extention || {}
  157. if !data['query']['bool']
  158. data['query']['bool'] = {}
  159. end
  160. if !data['query']['bool']['must']
  161. data['query']['bool']['must'] = []
  162. end
  163. # add * on simple query like "somephrase23" or "attribute: somephrase23"
  164. if query.present?
  165. query.strip!
  166. if query =~ /^([[:alpha:],0-9]+|[[:alpha:],0-9]+\:\s+[[:alpha:],0-9]+)$/
  167. query += '*'
  168. end
  169. end
  170. # real search condition
  171. condition = {
  172. 'query_string' => {
  173. 'query' => query,
  174. 'default_operator' => 'AND',
  175. }
  176. }
  177. data['query']['bool']['must'].push condition
  178. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  179. Rails.logger.debug " -d'#{data.to_json}'"
  180. response = UserAgent.get(
  181. url,
  182. data,
  183. {
  184. json: true,
  185. open_timeout: 5,
  186. read_timeout: 14,
  187. user: Setting.get('es_user'),
  188. password: Setting.get('es_password'),
  189. }
  190. )
  191. Rails.logger.info "# #{response.code}"
  192. if !response.success?
  193. Rails.logger.error "ERROR: POST on #{url}\n#{response.inspect}"
  194. return []
  195. end
  196. data = response.data
  197. ids = []
  198. return ids if !data
  199. return ids if !data['hits']
  200. return ids if !data['hits']['hits']
  201. data['hits']['hits'].each do |item|
  202. Rails.logger.info "... #{item['_type']} #{item['_id']}"
  203. data = {
  204. id: item['_id'],
  205. type: item['_type'],
  206. }
  207. ids.push data
  208. end
  209. ids
  210. end
  211. =begin
  212. get count of tickets and tickets which match on selector
  213. aggs_interval = {
  214. from: '2015-01-01',
  215. to: '2015-12-31',
  216. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  217. field: 'created_at',
  218. }
  219. result = SearchIndexBackend.selectors(index, params[:condition], limit, current_user, aggs_interval)
  220. # for aggregations
  221. result = {
  222. hits:{
  223. total:4819,
  224. },
  225. aggregations:{
  226. time_buckets:{
  227. buckets:[
  228. {
  229. key_as_string:"2014-10-01T00:00:00.000Z",
  230. key:1412121600000,
  231. doc_count:420
  232. },
  233. {
  234. key_as_string:"2014-11-01T00:00:00.000Z",
  235. key:1414800000000,
  236. doc_count:561
  237. },
  238. ...
  239. ]
  240. }
  241. }
  242. }
  243. =end
  244. def self.selectors(index = nil, selectors = nil, limit = 10, current_user = nil, aggs_interval = nil)
  245. raise 'no selectors given' if !selectors
  246. url = build_url()
  247. return if !url
  248. url += if index
  249. if index.class == Array
  250. "/#{index.join(',')}/_search"
  251. else
  252. "/#{index}/_search"
  253. end
  254. else
  255. '/_search'
  256. end
  257. data = selector2query(selectors, current_user, aggs_interval, limit)
  258. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  259. Rails.logger.debug " -d'#{data.to_json}'"
  260. response = UserAgent.get(
  261. url,
  262. data,
  263. {
  264. json: true,
  265. open_timeout: 5,
  266. read_timeout: 14,
  267. user: Setting.get('es_user'),
  268. password: Setting.get('es_password'),
  269. }
  270. )
  271. Rails.logger.info "# #{response.code}"
  272. if !response.success?
  273. raise "Unable to process POST at #{url}\n#{response.inspect}"
  274. end
  275. Rails.logger.debug response.data.to_json
  276. if !aggs_interval || !aggs_interval[:interval]
  277. ticket_ids = []
  278. response.data['hits']['hits'].each do |item|
  279. ticket_ids.push item['_id']
  280. end
  281. return {
  282. count: response.data['hits']['total'],
  283. ticket_ids: ticket_ids,
  284. }
  285. end
  286. response.data
  287. end
  288. def self.selector2query(selector, _current_user, aggs_interval, limit)
  289. query_must = []
  290. query_must_not = []
  291. if selector && !selector.empty?
  292. selector.each do |key, data|
  293. key_tmp = key.sub(/^.+?\./, '')
  294. t = {}
  295. if data['value'].class == Array
  296. t[:terms] = {}
  297. t[:terms][key_tmp] = data['value']
  298. else
  299. t[:term] = {}
  300. t[:term][key_tmp] = data['value']
  301. end
  302. if data['operator'] == 'is'
  303. query_must.push t
  304. elsif data['operator'] == 'is not'
  305. query_must_not.push t
  306. elsif data['operator'] == 'contains'
  307. query_must.push t
  308. elsif data['operator'] == 'contains not'
  309. query_must_not.push t
  310. else
  311. raise "unknown operator '#{data['operator']}'"
  312. end
  313. end
  314. end
  315. data = {
  316. query: {},
  317. size: limit,
  318. }
  319. # add aggs to filter
  320. if aggs_interval
  321. if aggs_interval[:interval]
  322. data[:size] = 0
  323. data[:aggs] = {
  324. time_buckets: {
  325. date_histogram: {
  326. field: aggs_interval[:field],
  327. interval: aggs_interval[:interval],
  328. }
  329. }
  330. }
  331. end
  332. r = {}
  333. r[:range] = {}
  334. r[:range][aggs_interval[:field]] = {
  335. from: aggs_interval[:from],
  336. to: aggs_interval[:to],
  337. }
  338. query_must.push r
  339. end
  340. if !data[:query][:bool]
  341. data[:query][:bool] = {}
  342. end
  343. if !query_must.empty?
  344. data[:query][:bool][:must] = query_must
  345. end
  346. if !query_must_not.empty?
  347. data[:query][:bool][:must_not] = query_must_not
  348. end
  349. # add sort
  350. if aggs_interval && aggs_interval[:field] && !aggs_interval[:interval]
  351. sort = []
  352. sort[0] = {}
  353. sort[0][aggs_interval[:field]] = {
  354. order: 'desc'
  355. }
  356. sort[1] = '_score'
  357. data['sort'] = sort
  358. end
  359. data
  360. end
  361. =begin
  362. return true if backend is configured
  363. result = SearchIndexBackend.enabled?
  364. =end
  365. def self.enabled?
  366. return false if Setting.get('es_url').blank?
  367. true
  368. end
  369. def self.build_url(type = nil, o_id = nil)
  370. return if !SearchIndexBackend.enabled?
  371. index = "#{Setting.get('es_index')}_#{Rails.env}"
  372. url = Setting.get('es_url')
  373. url = if type
  374. if o_id
  375. "#{url}/#{index}/#{type}/#{o_id}"
  376. else
  377. "#{url}/#{index}/#{type}"
  378. end
  379. else
  380. "#{url}/#{index}"
  381. end
  382. url
  383. end
  384. end