search_index_backend.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. # Copyright (C) 2012-2013 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. 'attachments' => { :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 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 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 drop index: " + 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. url = build_url()
  122. return if !url
  123. url += if index
  124. if index.class == Array
  125. "/#{index.join(',')}/_search"
  126. else
  127. "/#{index}/_search"
  128. end
  129. else
  130. '/_search'
  131. end
  132. data = {}
  133. data['from'] = 0
  134. data['size'] = limit
  135. data['sort'] =
  136. [
  137. {
  138. updated_at: {
  139. order: 'desc'
  140. }
  141. },
  142. '_score'
  143. ]
  144. data['query'] = query_extention || {}
  145. if !data['query']['bool']
  146. data['query']['bool'] = {}
  147. end
  148. if !data['query']['bool']['must']
  149. data['query']['bool']['must'] = []
  150. end
  151. # add * on simple query search
  152. if query && query =~ /^\w+$/
  153. query += '*'
  154. end
  155. # real search condition
  156. condition = {
  157. 'query_string' => {
  158. 'query' => query
  159. }
  160. }
  161. data['query']['bool']['must'].push condition
  162. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  163. Rails.logger.debug " -d'#{data.to_json}'"
  164. response = UserAgent.get(
  165. url,
  166. data,
  167. {
  168. json: true,
  169. open_timeout: 5,
  170. read_timeout: 14,
  171. user: Setting.get('es_user'),
  172. password: Setting.get('es_password'),
  173. }
  174. )
  175. Rails.logger.info "# #{response.code}"
  176. if !response.success?
  177. Rails.logger.error "ERROR: #{response.inspect}"
  178. return []
  179. end
  180. data = response.data
  181. ids = []
  182. return ids if !data
  183. return ids if !data['hits']
  184. return ids if !data['hits']['hits']
  185. data['hits']['hits'].each { |item|
  186. Rails.logger.info "... #{item['_type']} #{item['_id']}"
  187. data = {
  188. id: item['_id'],
  189. type: item['_type'],
  190. }
  191. ids.push data
  192. }
  193. ids
  194. end
  195. =begin
  196. get count of tickets and tickets which match on selector
  197. aggs_interval = {
  198. from: '2015-01-01',
  199. to: '2015-12-31',
  200. interval: 'month', # year, quarter, month, week, day, hour, minute, second
  201. field: 'created_at',
  202. }
  203. result = SearchIndexBackend.selectors(index, params[:condition], limit, current_user, aggs_interval)
  204. # for aggregations
  205. result = {
  206. hits:{
  207. total:4819,
  208. },
  209. aggregations:{
  210. time_buckets:{
  211. buckets:[
  212. {
  213. key_as_string:"2014-10-01T00:00:00.000Z",
  214. key:1412121600000,
  215. doc_count:420
  216. },
  217. {
  218. key_as_string:"2014-11-01T00:00:00.000Z",
  219. key:1414800000000,
  220. doc_count:561
  221. },
  222. ...
  223. ]
  224. }
  225. }
  226. }
  227. =end
  228. def self.selectors(index = nil, selectors = nil, limit = 10, current_user = nil, aggs_interval = nil)
  229. raise 'no selectors given' if !selectors
  230. url = build_url()
  231. return if !url
  232. url += if index
  233. if index.class == Array
  234. "/#{index.join(',')}/_search"
  235. else
  236. "/#{index}/_search"
  237. end
  238. else
  239. '/_search'
  240. end
  241. data = selector2query(selectors, current_user, aggs_interval, limit)
  242. Rails.logger.info "# curl -X POST \"#{url}\" \\"
  243. Rails.logger.debug " -d'#{data.to_json}'"
  244. response = UserAgent.get(
  245. url,
  246. data,
  247. {
  248. json: true,
  249. open_timeout: 5,
  250. read_timeout: 14,
  251. user: Setting.get('es_user'),
  252. password: Setting.get('es_password'),
  253. }
  254. )
  255. Rails.logger.info "# #{response.code}"
  256. if !response.success?
  257. raise "ERROR: #{response.inspect}"
  258. end
  259. Rails.logger.debug response.data.to_json
  260. if !aggs_interval || !aggs_interval[:interval]
  261. ticket_ids = []
  262. response.data['hits']['hits'].each {|item|
  263. ticket_ids.push item['_id']
  264. }
  265. return {
  266. count: response.data['hits']['total'],
  267. ticket_ids: ticket_ids,
  268. }
  269. end
  270. response.data
  271. end
  272. def self.selector2query(selector, _current_user, aggs_interval, limit)
  273. filter_must = []
  274. filter_must_not = []
  275. query_must = []
  276. query_must_not = []
  277. if selector && !selector.empty?
  278. selector.each {|key, data|
  279. key_tmp = key.sub(/^.+?\./, '')
  280. t = {}
  281. if data['value'].class == Array
  282. t[:terms] = {}
  283. t[:terms][key_tmp] = data['value']
  284. else
  285. t[:term] = {}
  286. t[:term][key_tmp] = data['value']
  287. end
  288. if data['operator'] == 'is'
  289. filter_must.push t
  290. elsif data['operator'] == 'is not'
  291. filter_must_not.push t
  292. elsif data['operator'] == 'contains'
  293. query_must.push t
  294. elsif data['operator'] == 'contains not'
  295. query_must_not.push t
  296. else
  297. raise "unknown operator '#{data['operator']}'"
  298. end
  299. }
  300. end
  301. data = {
  302. query: {},
  303. size: limit,
  304. }
  305. # add aggs to filter
  306. if aggs_interval
  307. if aggs_interval[:interval]
  308. data[:size] = 0
  309. data[:aggs] = {
  310. time_buckets: {
  311. date_histogram: {
  312. field: aggs_interval[:field],
  313. interval: aggs_interval[:interval],
  314. }
  315. }
  316. }
  317. end
  318. r = {}
  319. r[:range] = {}
  320. r[:range][aggs_interval[:field]] = {
  321. from: aggs_interval[:from],
  322. to: aggs_interval[:to],
  323. }
  324. filter_must.push r
  325. end
  326. if !query_must.empty? || !query_must_not.empty?
  327. if !data[:query][:filtered]
  328. data[:query][:filtered] = {}
  329. end
  330. if !data[:query][:filtered][:query]
  331. data[:query][:filtered][:query] = {}
  332. end
  333. if !data[:query][:filtered][:query][:bool]
  334. data[:query][:filtered][:query][:bool] = {}
  335. end
  336. end
  337. if !query_must.empty?
  338. data[:query][:filtered][:query][:bool][:must] = query_must
  339. end
  340. if !query_must_not.empty?
  341. data[:query][:filtered][:query][:bool][:must_not] = query_must_not
  342. end
  343. if !filter_must.empty? || !filter_must.empty?
  344. if !data[:query][:filtered]
  345. data[:query][:filtered] = {}
  346. end
  347. if !data[:query][:filtered][:filter]
  348. data[:query][:filtered][:filter] = {}
  349. end
  350. if !data[:query][:filtered][:filter][:bool]
  351. data[:query][:filtered][:filter][:bool] = {}
  352. end
  353. end
  354. if !filter_must.empty?
  355. data[:query][:filtered][:filter][:bool][:must] = filter_must
  356. end
  357. if !filter_must_not.empty?
  358. data[:query][:filtered][:filter][:bool][:must_not] = filter_must_not
  359. end
  360. # add sort
  361. if aggs_interval && aggs_interval[:field] && !aggs_interval[:interval]
  362. sort = []
  363. sort[0] = {}
  364. sort[0][aggs_interval[:field]] = {
  365. order: 'desc'
  366. }
  367. sort[1] = '_score'
  368. data['sort'] = sort
  369. end
  370. data
  371. end
  372. =begin
  373. return true if backend is configured
  374. result = SearchIndexBackend.enabled?
  375. =end
  376. def self.enabled?
  377. return if !Setting.get('es_url')
  378. return if Setting.get('es_url').empty?
  379. true
  380. end
  381. def self.build_url( type = nil, o_id = nil )
  382. return if !SearchIndexBackend.enabled?
  383. index = Setting.get('es_index').to_s + "_#{Rails.env}"
  384. url = Setting.get('es_url')
  385. url = if type
  386. if o_id
  387. "#{url}/#{index}/#{type}/#{o_id}"
  388. else
  389. "#{url}/#{index}/#{type}"
  390. end
  391. else
  392. "#{url}/#{index}"
  393. end
  394. url
  395. end
  396. end