chewy 0.9.0 → 0.10.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (265) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +1 -0
  3. data/.rubocop.yml +24 -2
  4. data/.rubocop_todo.yml +2 -2
  5. data/.travis.yml +38 -21
  6. data/.yardopts +5 -0
  7. data/Appraisals +55 -27
  8. data/CHANGELOG.md +57 -12
  9. data/Gemfile +14 -10
  10. data/LEGACY_DSL.md +497 -0
  11. data/README.md +249 -515
  12. data/chewy.gemspec +5 -4
  13. data/gemfiles/rails.4.0.activerecord.gemfile +14 -0
  14. data/gemfiles/rails.4.1.activerecord.gemfile +14 -0
  15. data/gemfiles/rails.4.2.activerecord.gemfile +8 -10
  16. data/gemfiles/rails.4.2.mongoid.5.1.gemfile +9 -10
  17. data/gemfiles/rails.5.0.activerecord.gemfile +8 -10
  18. data/gemfiles/rails.5.0.mongoid.6.0.gemfile +15 -0
  19. data/gemfiles/rails.5.1.activerecord.gemfile +15 -0
  20. data/gemfiles/rails.5.1.mongoid.6.1.gemfile +15 -0
  21. data/gemfiles/sequel.4.45.gemfile +11 -0
  22. data/lib/chewy.rb +77 -43
  23. data/lib/chewy/config.rb +44 -7
  24. data/lib/chewy/errors.rb +2 -2
  25. data/lib/chewy/fields/base.rb +39 -32
  26. data/lib/chewy/fields/root.rb +33 -7
  27. data/lib/chewy/index.rb +237 -149
  28. data/lib/chewy/index/actions.rb +85 -28
  29. data/lib/chewy/index/aliases.rb +2 -1
  30. data/lib/chewy/index/settings.rb +9 -5
  31. data/lib/chewy/index/specification.rb +58 -0
  32. data/lib/chewy/journal.rb +40 -92
  33. data/lib/chewy/query.rb +43 -27
  34. data/lib/chewy/query/compose.rb +13 -13
  35. data/lib/chewy/query/criteria.rb +13 -13
  36. data/lib/chewy/query/filters.rb +1 -1
  37. data/lib/chewy/query/loading.rb +1 -1
  38. data/lib/chewy/query/nodes/and.rb +2 -2
  39. data/lib/chewy/query/nodes/bool.rb +1 -1
  40. data/lib/chewy/query/nodes/equal.rb +2 -2
  41. data/lib/chewy/query/nodes/exists.rb +1 -1
  42. data/lib/chewy/query/nodes/has_relation.rb +2 -2
  43. data/lib/chewy/query/nodes/match_all.rb +1 -1
  44. data/lib/chewy/query/nodes/missing.rb +1 -1
  45. data/lib/chewy/query/nodes/not.rb +2 -2
  46. data/lib/chewy/query/nodes/or.rb +2 -2
  47. data/lib/chewy/query/nodes/prefix.rb +1 -1
  48. data/lib/chewy/query/nodes/query.rb +2 -2
  49. data/lib/chewy/query/nodes/range.rb +4 -4
  50. data/lib/chewy/query/nodes/regexp.rb +4 -4
  51. data/lib/chewy/query/nodes/script.rb +3 -3
  52. data/lib/chewy/query/pagination.rb +10 -1
  53. data/lib/chewy/railtie.rb +1 -0
  54. data/lib/chewy/rake_helper.rb +265 -48
  55. data/lib/chewy/rspec/update_index.rb +30 -22
  56. data/lib/chewy/search.rb +78 -21
  57. data/lib/chewy/search/loader.rb +83 -0
  58. data/lib/chewy/{query → search}/pagination/kaminari.rb +13 -5
  59. data/lib/chewy/search/pagination/will_paginate.rb +41 -0
  60. data/lib/chewy/search/parameters.rb +150 -0
  61. data/lib/chewy/search/parameters/aggs.rb +16 -0
  62. data/lib/chewy/search/parameters/concerns/bool_storage.rb +24 -0
  63. data/lib/chewy/search/parameters/concerns/hash_storage.rb +23 -0
  64. data/lib/chewy/search/parameters/concerns/integer_storage.rb +14 -0
  65. data/lib/chewy/search/parameters/concerns/query_storage.rb +237 -0
  66. data/lib/chewy/search/parameters/concerns/string_array_storage.rb +23 -0
  67. data/lib/chewy/search/parameters/concerns/string_storage.rb +14 -0
  68. data/lib/chewy/search/parameters/docvalue_fields.rb +12 -0
  69. data/lib/chewy/search/parameters/explain.rb +16 -0
  70. data/lib/chewy/search/parameters/filter.rb +47 -0
  71. data/lib/chewy/search/parameters/highlight.rb +16 -0
  72. data/lib/chewy/search/parameters/indices_boost.rb +52 -0
  73. data/lib/chewy/search/parameters/limit.rb +17 -0
  74. data/lib/chewy/search/parameters/load.rb +32 -0
  75. data/lib/chewy/search/parameters/min_score.rb +16 -0
  76. data/lib/chewy/search/parameters/none.rb +27 -0
  77. data/lib/chewy/search/parameters/offset.rb +17 -0
  78. data/lib/chewy/search/parameters/order.rb +64 -0
  79. data/lib/chewy/search/parameters/post_filter.rb +19 -0
  80. data/lib/chewy/search/parameters/preference.rb +16 -0
  81. data/lib/chewy/search/parameters/profile.rb +16 -0
  82. data/lib/chewy/search/parameters/query.rb +19 -0
  83. data/lib/chewy/search/parameters/request_cache.rb +27 -0
  84. data/lib/chewy/search/parameters/rescore.rb +29 -0
  85. data/lib/chewy/search/parameters/script_fields.rb +16 -0
  86. data/lib/chewy/search/parameters/search_after.rb +20 -0
  87. data/lib/chewy/search/parameters/search_type.rb +16 -0
  88. data/lib/chewy/search/parameters/source.rb +73 -0
  89. data/lib/chewy/search/parameters/storage.rb +95 -0
  90. data/lib/chewy/search/parameters/stored_fields.rb +63 -0
  91. data/lib/chewy/search/parameters/suggest.rb +16 -0
  92. data/lib/chewy/search/parameters/terminate_after.rb +16 -0
  93. data/lib/chewy/search/parameters/timeout.rb +16 -0
  94. data/lib/chewy/search/parameters/track_scores.rb +16 -0
  95. data/lib/chewy/search/parameters/types.rb +20 -0
  96. data/lib/chewy/search/parameters/version.rb +16 -0
  97. data/lib/chewy/search/query_proxy.rb +257 -0
  98. data/lib/chewy/search/request.rb +1021 -0
  99. data/lib/chewy/search/response.rb +119 -0
  100. data/lib/chewy/search/scoping.rb +50 -0
  101. data/lib/chewy/search/scrolling.rb +136 -0
  102. data/lib/chewy/stash.rb +70 -0
  103. data/lib/chewy/strategy.rb +10 -3
  104. data/lib/chewy/strategy/active_job.rb +1 -0
  105. data/lib/chewy/strategy/atomic.rb +1 -3
  106. data/lib/chewy/strategy/bypass.rb +1 -1
  107. data/lib/chewy/strategy/resque.rb +1 -0
  108. data/lib/chewy/strategy/shoryuken.rb +40 -0
  109. data/lib/chewy/strategy/sidekiq.rb +13 -3
  110. data/lib/chewy/type.rb +29 -7
  111. data/lib/chewy/type/actions.rb +26 -2
  112. data/lib/chewy/type/adapter/active_record.rb +44 -29
  113. data/lib/chewy/type/adapter/base.rb +27 -7
  114. data/lib/chewy/type/adapter/mongoid.rb +18 -7
  115. data/lib/chewy/type/adapter/object.rb +187 -26
  116. data/lib/chewy/type/adapter/orm.rb +59 -32
  117. data/lib/chewy/type/adapter/sequel.rb +32 -16
  118. data/lib/chewy/type/import.rb +145 -191
  119. data/lib/chewy/type/import/bulk_builder.rb +122 -0
  120. data/lib/chewy/type/import/bulk_request.rb +76 -0
  121. data/lib/chewy/type/import/journal_builder.rb +45 -0
  122. data/lib/chewy/type/import/routine.rb +138 -0
  123. data/lib/chewy/type/mapping.rb +11 -1
  124. data/lib/chewy/type/observe.rb +1 -1
  125. data/lib/chewy/type/syncer.rb +220 -0
  126. data/lib/chewy/type/witchcraft.rb +27 -13
  127. data/lib/chewy/type/wrapper.rb +28 -2
  128. data/lib/chewy/version.rb +1 -1
  129. data/lib/tasks/chewy.rake +84 -26
  130. data/spec/chewy/config_spec.rb +82 -1
  131. data/spec/chewy/fields/base_spec.rb +147 -112
  132. data/spec/chewy/fields/root_spec.rb +75 -18
  133. data/spec/chewy/fields/time_fields_spec.rb +2 -3
  134. data/spec/chewy/index/actions_spec.rb +180 -50
  135. data/spec/chewy/index/aliases_spec.rb +2 -2
  136. data/spec/chewy/index/settings_spec.rb +67 -38
  137. data/spec/chewy/index/specification_spec.rb +160 -0
  138. data/spec/chewy/index_spec.rb +57 -66
  139. data/spec/chewy/journal_spec.rb +149 -54
  140. data/spec/chewy/minitest/helpers_spec.rb +4 -4
  141. data/spec/chewy/minitest/search_index_receiver_spec.rb +1 -1
  142. data/spec/chewy/query/criteria_spec.rb +179 -179
  143. data/spec/chewy/query/filters_spec.rb +15 -15
  144. data/spec/chewy/query/loading_spec.rb +22 -20
  145. data/spec/chewy/query/nodes/and_spec.rb +2 -2
  146. data/spec/chewy/query/nodes/bool_spec.rb +4 -4
  147. data/spec/chewy/query/nodes/equal_spec.rb +19 -19
  148. data/spec/chewy/query/nodes/exists_spec.rb +6 -6
  149. data/spec/chewy/query/nodes/has_child_spec.rb +19 -19
  150. data/spec/chewy/query/nodes/has_parent_spec.rb +19 -19
  151. data/spec/chewy/query/nodes/missing_spec.rb +5 -5
  152. data/spec/chewy/query/nodes/not_spec.rb +3 -2
  153. data/spec/chewy/query/nodes/or_spec.rb +2 -2
  154. data/spec/chewy/query/nodes/prefix_spec.rb +5 -5
  155. data/spec/chewy/query/nodes/query_spec.rb +2 -2
  156. data/spec/chewy/query/nodes/range_spec.rb +18 -18
  157. data/spec/chewy/query/nodes/raw_spec.rb +1 -1
  158. data/spec/chewy/query/nodes/regexp_spec.rb +14 -14
  159. data/spec/chewy/query/nodes/script_spec.rb +4 -4
  160. data/spec/chewy/query/pagination/kaminari_spec.rb +3 -55
  161. data/spec/chewy/query/pagination/will_paginate_spec.rb +5 -0
  162. data/spec/chewy/query/pagination_spec.rb +25 -21
  163. data/spec/chewy/query_spec.rb +501 -560
  164. data/spec/chewy/rake_helper_spec.rb +368 -0
  165. data/spec/chewy/repository_spec.rb +4 -4
  166. data/spec/chewy/rspec/update_index_spec.rb +89 -56
  167. data/spec/chewy/runtime_spec.rb +2 -2
  168. data/spec/chewy/search/loader_spec.rb +117 -0
  169. data/spec/chewy/search/pagination/kaminari_examples.rb +71 -0
  170. data/spec/chewy/search/pagination/kaminari_spec.rb +17 -0
  171. data/spec/chewy/search/pagination/will_paginate_examples.rb +63 -0
  172. data/spec/chewy/search/pagination/will_paginate_spec.rb +17 -0
  173. data/spec/chewy/search/parameters/aggs_spec.rb +5 -0
  174. data/spec/chewy/search/parameters/bool_storage_examples.rb +53 -0
  175. data/spec/chewy/search/parameters/docvalue_fields_spec.rb +5 -0
  176. data/spec/chewy/search/parameters/explain_spec.rb +5 -0
  177. data/spec/chewy/search/parameters/filter_spec.rb +5 -0
  178. data/spec/chewy/search/parameters/hash_storage_examples.rb +59 -0
  179. data/spec/chewy/search/parameters/highlight_spec.rb +5 -0
  180. data/spec/chewy/search/parameters/indices_boost_spec.rb +83 -0
  181. data/spec/chewy/search/parameters/integer_storage_examples.rb +32 -0
  182. data/spec/chewy/search/parameters/limit_spec.rb +5 -0
  183. data/spec/chewy/search/parameters/load_spec.rb +60 -0
  184. data/spec/chewy/search/parameters/min_score_spec.rb +32 -0
  185. data/spec/chewy/search/parameters/none_spec.rb +5 -0
  186. data/spec/chewy/search/parameters/offset_spec.rb +5 -0
  187. data/spec/chewy/search/parameters/order_spec.rb +65 -0
  188. data/spec/chewy/search/parameters/post_filter_spec.rb +5 -0
  189. data/spec/chewy/search/parameters/preference_spec.rb +5 -0
  190. data/spec/chewy/search/parameters/profile_spec.rb +5 -0
  191. data/spec/chewy/search/parameters/query_spec.rb +5 -0
  192. data/spec/chewy/search/parameters/query_storage_examples.rb +388 -0
  193. data/spec/chewy/search/parameters/request_cache_spec.rb +67 -0
  194. data/spec/chewy/search/parameters/rescore_spec.rb +62 -0
  195. data/spec/chewy/search/parameters/script_fields_spec.rb +5 -0
  196. data/spec/chewy/search/parameters/search_after_spec.rb +32 -0
  197. data/spec/chewy/search/parameters/search_type_spec.rb +5 -0
  198. data/spec/chewy/search/parameters/source_spec.rb +156 -0
  199. data/spec/chewy/search/parameters/storage_spec.rb +60 -0
  200. data/spec/chewy/search/parameters/stored_fields_spec.rb +126 -0
  201. data/spec/chewy/search/parameters/string_array_storage_examples.rb +63 -0
  202. data/spec/chewy/search/parameters/string_storage_examples.rb +32 -0
  203. data/spec/chewy/search/parameters/suggest_spec.rb +5 -0
  204. data/spec/chewy/search/parameters/terminate_after_spec.rb +5 -0
  205. data/spec/chewy/search/parameters/timeout_spec.rb +5 -0
  206. data/spec/chewy/search/parameters/track_scores_spec.rb +5 -0
  207. data/spec/chewy/search/parameters/types_spec.rb +5 -0
  208. data/spec/chewy/search/parameters/version_spec.rb +5 -0
  209. data/spec/chewy/search/parameters_spec.rb +130 -0
  210. data/spec/chewy/search/query_proxy_spec.rb +68 -0
  211. data/spec/chewy/search/request_spec.rb +669 -0
  212. data/spec/chewy/search/response_spec.rb +192 -0
  213. data/spec/chewy/search/scrolling_spec.rb +169 -0
  214. data/spec/chewy/search_spec.rb +13 -6
  215. data/spec/chewy/stash_spec.rb +95 -0
  216. data/spec/chewy/strategy/active_job_spec.rb +6 -0
  217. data/spec/chewy/strategy/resque_spec.rb +6 -0
  218. data/spec/chewy/strategy/shoryuken_spec.rb +64 -0
  219. data/spec/chewy/strategy/sidekiq_spec.rb +8 -0
  220. data/spec/chewy/strategy_spec.rb +6 -6
  221. data/spec/chewy/type/actions_spec.rb +29 -10
  222. data/spec/chewy/type/adapter/active_record_spec.rb +203 -91
  223. data/spec/chewy/type/adapter/mongoid_spec.rb +112 -54
  224. data/spec/chewy/type/adapter/object_spec.rb +101 -28
  225. data/spec/chewy/type/adapter/sequel_spec.rb +149 -82
  226. data/spec/chewy/type/import/bulk_builder_spec.rb +279 -0
  227. data/spec/chewy/type/import/bulk_request_spec.rb +102 -0
  228. data/spec/chewy/type/import/journal_builder_spec.rb +95 -0
  229. data/spec/chewy/type/import/routine_spec.rb +110 -0
  230. data/spec/chewy/type/import_spec.rb +350 -271
  231. data/spec/chewy/type/mapping_spec.rb +54 -18
  232. data/spec/chewy/type/observe_spec.rb +5 -1
  233. data/spec/chewy/type/syncer_spec.rb +123 -0
  234. data/spec/chewy/type/witchcraft_spec.rb +45 -29
  235. data/spec/chewy/type/wrapper_spec.rb +63 -23
  236. data/spec/chewy/type_spec.rb +28 -7
  237. data/spec/chewy_spec.rb +75 -7
  238. data/spec/spec_helper.rb +5 -2
  239. data/spec/support/active_record.rb +5 -1
  240. data/spec/support/class_helpers.rb +0 -14
  241. data/spec/support/mongoid.rb +15 -3
  242. data/spec/support/sequel.rb +6 -1
  243. metadata +198 -37
  244. data/gemfiles/rails.3.2.activerecord.gemfile +0 -16
  245. data/gemfiles/rails.3.2.activerecord.kaminari.gemfile +0 -15
  246. data/gemfiles/rails.3.2.activerecord.will_paginate.gemfile +0 -15
  247. data/gemfiles/rails.4.2.activerecord.kaminari.gemfile +0 -16
  248. data/gemfiles/rails.4.2.activerecord.will_paginate.gemfile +0 -16
  249. data/gemfiles/rails.4.2.mongoid.4.0.gemfile +0 -16
  250. data/gemfiles/rails.4.2.mongoid.4.0.kaminari.gemfile +0 -15
  251. data/gemfiles/rails.4.2.mongoid.4.0.will_paginate.gemfile +0 -15
  252. data/gemfiles/rails.4.2.mongoid.5.1.kaminari.gemfile +0 -15
  253. data/gemfiles/rails.4.2.mongoid.5.1.will_paginate.gemfile +0 -15
  254. data/gemfiles/rails.5.0.activerecord.kaminari.gemfile +0 -16
  255. data/gemfiles/rails.5.0.activerecord.will_paginate.gemfile +0 -16
  256. data/gemfiles/sequel.4.38.gemfile +0 -14
  257. data/lib/chewy/journal/apply.rb +0 -31
  258. data/lib/chewy/journal/clean.rb +0 -24
  259. data/lib/chewy/journal/entry.rb +0 -83
  260. data/lib/chewy/journal/query.rb +0 -87
  261. data/lib/chewy/query/pagination/will_paginate.rb +0 -27
  262. data/lib/chewy/query/scoping.rb +0 -20
  263. data/spec/chewy/journal/apply_spec.rb +0 -120
  264. data/spec/chewy/journal/entry_spec.rb +0 -237
  265. data/spec/chewy/query/pagination/will_paginage_spec.rb +0 -59
@@ -99,22 +99,19 @@ RSpec::Matchers.define :update_index do |type_name, options = {}| # rubocop:disa
99
99
  @delete ||= {}
100
100
  @missed_reindex = []
101
101
  @missed_delete = []
102
- @updated = []
103
102
 
104
- instance_eval <<-RUBY, __FILE__, __LINE__ + 1
105
- type = Chewy.derive_type(type_name)
106
- #{agnostic_stub} do |bulk_options|
107
- @updated += bulk_options[:body].map do |updated_document|
108
- updated_document.deep_symbolize_keys
109
- end
110
- {}
111
- end
112
- RUBY
103
+ type = Chewy.derive_type(type_name)
104
+ if defined?(Mocha) && RSpec.configuration.mock_framework.to_s == 'RSpec::Core::MockingAdapters::Mocha'
105
+ Chewy::Type::Import::BulkRequest.stubs(:new).with(type, any_parameters).returns(mock_bulk_request)
106
+ else
107
+ mocked_already = ::RSpec::Mocks.space.proxy_for(Chewy::Type::Import::BulkRequest).method_double_if_exists_for_message(:new)
108
+ allow(Chewy::Type::Import::BulkRequest).to receive(:new).and_call_original unless mocked_already
109
+ allow(Chewy::Type::Import::BulkRequest).to receive(:new).with(type, any_args).and_return(mock_bulk_request)
110
+ end
113
111
 
114
- ActiveSupport::Deprecation.warn('`atomic: false` option is removed and not effective anymore, use `strategy: :atomic` option instead') if options.key?(:atomic)
115
112
  Chewy.strategy(options[:strategy] || :atomic) { block.call }
116
113
 
117
- @updated.each do |updated_document|
114
+ mock_bulk_request.updates.each do |updated_document|
118
115
  if (body = updated_document[:index])
119
116
  if (document = @reindex[body[:_id].to_s])
120
117
  document[:real_count] += 1
@@ -142,7 +139,7 @@ RSpec::Matchers.define :update_index do |type_name, options = {}| # rubocop:disa
142
139
  (document[:expected_count] && document[:expected_count] == document[:real_count])
143
140
  end
144
141
 
145
- @updated.present? && @missed_reindex.none? && @missed_delete.none? &&
142
+ mock_bulk_request.updates.present? && @missed_reindex.none? && @missed_delete.none? &&
146
143
  @reindex.all? { |_, document| document[:match_count] && document[:match_attributes] } &&
147
144
  @delete.all? { |_, document| document[:match_count] }
148
145
  end
@@ -150,7 +147,7 @@ RSpec::Matchers.define :update_index do |type_name, options = {}| # rubocop:disa
150
147
  failure_message do # rubocop:disable BlockLength
151
148
  output = ''
152
149
 
153
- if @updated.none?
150
+ if mock_bulk_request.updates.none?
154
151
  output << "Expected index `#{type_name}` to be updated, but it was not\n"
155
152
  elsif @missed_reindex.present? || @missed_delete.present?
156
153
  message = "Expected index `#{type_name}` "
@@ -197,19 +194,15 @@ RSpec::Matchers.define :update_index do |type_name, options = {}| # rubocop:disa
197
194
  end
198
195
 
199
196
  failure_message_when_negated do
200
- if @updated.present?
201
- "Expected index `#{type_name}` not to be updated, but it was with #{@updated.map(&:values).flatten.group_by { |documents| documents[:_id] }.map do |id, documents|
197
+ if mock_bulk_request.updates.present?
198
+ "Expected index `#{type_name}` not to be updated, but it was with #{mock_bulk_request.updates.map(&:values).flatten.group_by { |documents| documents[:_id] }.map do |id, documents|
202
199
  "\n document id `#{id}` (#{documents.count} times)"
203
200
  end.join}\n"
204
201
  end
205
202
  end
206
203
 
207
- def agnostic_stub
208
- if defined?(Mocha) && RSpec.configuration.mock_framework.to_s == 'RSpec::Core::MockingAdapters::Mocha'
209
- 'type.stubs(:bulk).with'
210
- else
211
- 'allow(type).to receive(:bulk)'
212
- end
204
+ def mock_bulk_request
205
+ @mock_bulk_request ||= MockBulkRequest.new
213
206
  end
214
207
 
215
208
  def extract_documents(*args)
@@ -251,4 +244,19 @@ RSpec::Matchers.define :update_index do |type_name, options = {}| # rubocop:disa
251
244
  end
252
245
  difference.none?
253
246
  end
247
+
248
+ # Collects request bodies coming through the perform method for
249
+ # the further analysis.
250
+ class MockBulkRequest
251
+ attr_reader :updates
252
+
253
+ def initialize
254
+ @updates = []
255
+ end
256
+
257
+ def perform(body)
258
+ @updates.concat(body.map(&:deep_symbolize_keys))
259
+ []
260
+ end
261
+ end
254
262
  end
@@ -1,24 +1,62 @@
1
+ require 'chewy/search/scoping'
1
2
  require 'chewy/query'
3
+ require 'chewy/search/scrolling'
4
+ require 'chewy/search/query_proxy'
5
+ require 'chewy/search/parameters'
6
+ require 'chewy/search/response'
7
+ require 'chewy/search/loader'
8
+ require 'chewy/search/request'
9
+ require 'chewy/search/pagination/kaminari'
10
+ require 'chewy/search/pagination/will_paginate'
2
11
 
3
12
  module Chewy
13
+ # This module being included to any provides an interface to the
14
+ # request DSL. By default it is included to {Chewy::Index} and
15
+ # {Chewy::Type}.
16
+ #
17
+ # The class used as a request DSL provider is
18
+ # inherited from {Chewy::Search::Request} by default, but if you
19
+ # need ES < 2.0 DSL support - you can switch it to {Chewy::Query}
20
+ # using {Chewy::Config#search_class}
21
+ #
22
+ # Also, the search class is refined with one of the pagination-
23
+ # providing modules: {Chewy::Search::Pagination::Kaminari} or
24
+ # {Chewy::Search::Pagination::WillPaginate}.
25
+ #
26
+ # @example
27
+ # PlacesIndex.query(match: {name: 'Moscow'})
28
+ # PlacesIndex::City.query(match: {name: 'Moscow'})
29
+ # @see Chewy::Index
30
+ # @see Chewy::Type
31
+ # @see Chewy::Search::Request
32
+ # @see Chewy::Search::ClassMethods
33
+ # @see Chewy::Search::Pagination::Kaminari
34
+ # @see Chewy::Search::Pagination::WillPaginate
4
35
  module Search
5
36
  extend ActiveSupport::Concern
6
37
 
7
- included do
8
- singleton_class.delegate :explain, :query_mode, :filter_mode, :post_filter_mode,
9
- :timeout, :limit, :offset, :highlight, :min_score, :rescore, :facets, :script_score,
10
- :boost_factor, :weight, :random_score, :field_value_factor, :decay, :aggregations,
11
- :suggest, :none, :strategy, :query, :filter, :post_filter, :boost_mode,
12
- :score_mode, :order, :reorder, :only, :types, :delete_all, :find, :total,
13
- :total_count, :total_entries, :unlimited, :script_fields, :track_scores, :preference,
14
- to: :all
15
- end
16
-
17
38
  module ClassMethods
39
+ # This is the entry point for the request composition, however,
40
+ # most of the {Chewy::Search::Request} methods are delegated
41
+ # directly as well.
42
+ #
43
+ # This method also provides an ability to use names scopes.
44
+ #
45
+ # @example
46
+ # PlacesIndex.all.limit(10)
47
+ # # is basically the same as:
48
+ # PlacesIndex.limit(10)
49
+ # @see Chewy::Search::Request
50
+ # @see Chewy::Search::Scoping
51
+ # @return [Chewy::Search::Request] request instance
18
52
  def all
19
- query_class.scopes.last || query_class.new(self)
53
+ search_class.scopes.last || search_class.new(self)
20
54
  end
21
55
 
56
+ # A simple way to execute search string query.
57
+ #
58
+ # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-uri-request.html
59
+ # @return [Hash] the request result
22
60
  def search_string(query, options = {})
23
61
  options = options.merge(
24
62
  index: all._indexes.map(&:index_name),
@@ -28,20 +66,39 @@ module Chewy
28
66
  Chewy.client.search(options)
29
67
  end
30
68
 
69
+ # Delegates methods from the request class to the index or type class
70
+ #
71
+ # @example
72
+ # PlacesIndex.query(match: {name: 'Moscow'})
73
+ # PlacesIndex::City.query(match: {name: 'Moscow'})
74
+ def method_missing(name, *args, &block)
75
+ if search_class::DELEGATED_METHODS.include?(name)
76
+ all.send(name, *args, &block)
77
+ else
78
+ super
79
+ end
80
+ end
81
+
82
+ def respond_to_missing?(name, _)
83
+ search_class::DELEGATED_METHODS.include?(name) || super
84
+ end
85
+
31
86
  private
32
87
 
33
- def query_class
34
- @query_class ||= begin
35
- query_class = Class.new(Chewy::Query)
36
- if self < Chewy::Type
37
- index_scopes = index.scopes - scopes
88
+ def search_class
89
+ @search_class ||= build_search_class(Chewy.search_class)
90
+ end
38
91
 
39
- delegate_scoped index, query_class, index_scopes
40
- delegate_scoped index, self, index_scopes
41
- end
42
- delegate_scoped self, query_class, scopes
43
- const_set('Query', query_class)
92
+ def build_search_class(base)
93
+ search_class = Class.new(base)
94
+ if self < Chewy::Type
95
+ index_scopes = index.scopes - scopes
96
+
97
+ delegate_scoped index, search_class, index_scopes
98
+ delegate_scoped index, self, index_scopes
44
99
  end
100
+ delegate_scoped self, search_class, scopes
101
+ const_set('Query', search_class)
45
102
  end
46
103
 
47
104
  def delegate_scoped(source, destination, methods)
@@ -0,0 +1,83 @@
1
+ module Chewy
2
+ module Search
3
+ # This class is used for two different purposes: load ORM/ODM
4
+ # source objects.
5
+ #
6
+ # @see Chewy::Type::Import
7
+ # @see Chewy::Search::Request#load
8
+ # @see Chewy::Search::Response#objects
9
+ # @see Chewy::Search::Scrolling#scroll_objects
10
+ class Loader
11
+ # @param indexes [Array<Chewy::Index>] list of indexes to lookup types
12
+ # @param only [Array<String, Symbol>] list of selected type names to load
13
+ # @param except [Array<String, Symbol>] list of type names which will not be loaded
14
+ # @param options [Hash] adapter-specific load options
15
+ # @see Chewy::Type::Adapter::Base#load
16
+ def initialize(indexes: [], only: [], except: [], **options)
17
+ @indexes = indexes
18
+ @only = Array.wrap(only).map(&:to_s)
19
+ @except = Array.wrap(except).map(&:to_s)
20
+ @options = options
21
+ end
22
+
23
+ # Returns a {Chewy::Type} object for index name and type name passed. Caches
24
+ # the result for each pair to make lookup faster.
25
+ #
26
+ # @param index [String] index name
27
+ # @param type [String] type name
28
+ # @return [Chewy::Type]
29
+ # @raise [Chewy::UnderivableType] when index or hash were not found
30
+ def derive_type(index, type)
31
+ (@derive_type ||= {})[[index, type]] ||= begin
32
+ index_class = derive_index(index)
33
+ raise Chewy::UnderivableType, "Can not find index named `#{index}`" unless index_class
34
+ index_class.type_hash[type] or raise Chewy::UnderivableType, "Index `#{index}` doesn`t have type named `#{type}`"
35
+ end
36
+ end
37
+
38
+ # For each passed hit this method loads an ORM/ORD source object
39
+ # using `hit['_id']`. The returned array is exactly in the same order
40
+ # as hits were. If source object was not found for some hit, `nil`
41
+ # will be returned at the corresponding position in array.
42
+ #
43
+ # Records/documents are loaded in an efficient manner, performing
44
+ # a single query for each type present.
45
+ #
46
+ # @param hits [Array<Hash>] ES hits array
47
+ # @return [Array<Object, nil>] the array of corresponding ORM/ODM objects
48
+ def load(hits)
49
+ hit_groups = hits.group_by { |hit| [hit['_index'], hit['_type']] }
50
+ loaded_objects = hit_groups.each_with_object({}) do |((index_name, type_name), hit_group), result|
51
+ next if skip_type?(type_name)
52
+
53
+ type = derive_type(index_name, type_name)
54
+ ids = hit_group.map { |hit| hit['_id'] }
55
+ loaded = type.adapter.load(ids, @options.merge(_type: type))
56
+ loaded ||= hit_group.map { |hit| type.build(hit) }
57
+
58
+ result.merge!(hit_group.zip(loaded).to_h)
59
+ end
60
+
61
+ hits.map { |hit| loaded_objects[hit] }
62
+ end
63
+
64
+ private
65
+
66
+ def derive_index(index_name)
67
+ (@derive_index ||= {})[index_name] ||= indexes_hash[index_name] ||
68
+ indexes_hash[indexes_hash.keys.sort_by(&:length)
69
+ .reverse.detect do |name|
70
+ index_name.match(/#{name}(_.+|\z)/)
71
+ end]
72
+ end
73
+
74
+ def indexes_hash
75
+ @indexes_hash ||= @indexes.index_by(&:index_name)
76
+ end
77
+
78
+ def skip_type?(type_name)
79
+ @except.include?(type_name) || @only.present? && !@only.include?(type_name)
80
+ end
81
+ end
82
+ end
83
+ end
@@ -1,6 +1,12 @@
1
1
  module Chewy
2
- class Query
2
+ module Search
3
3
  module Pagination
4
+ # This module provides `Kaminari` support for {Chewy::Search::Request}
5
+ # It is included automatically if `Kaminari` is available.
6
+ #
7
+ # @example
8
+ # PlacesIndex.all.page(3).per(10).order(:name)
9
+ # # => <PlacesIndex::Query {..., :body=>{:size=>10, :from=>20, :sort=>["name"]}}>
4
10
  module Kaminari
5
11
  extend ActiveSupport::Concern
6
12
 
@@ -17,11 +23,11 @@ module Chewy
17
23
  end
18
24
 
19
25
  def limit_value
20
- (criteria.request_options[:size].presence || default_per_page).to_i
26
+ (raw_limit_value || default_per_page).to_i
21
27
  end
22
28
 
23
29
  def offset_value
24
- criteria.request_options[:from].to_i
30
+ raw_offset_value.to_i
25
31
  end
26
32
 
27
33
  private
@@ -29,9 +35,11 @@ module Chewy
29
35
  def _kaminari_config
30
36
  ::Kaminari.config
31
37
  end
38
+
39
+ def paginated_collection(collection)
40
+ ::Kaminari.paginate_array(collection, limit: limit_value, offset: offset_value, total_count: total_count)
41
+ end
32
42
  end
33
43
  end
34
44
  end
35
45
  end
36
-
37
- Chewy::Query.send :include, Chewy::Query::Pagination::Kaminari
@@ -0,0 +1,41 @@
1
+ module Chewy
2
+ module Search
3
+ module Pagination
4
+ # This module provides `WillPaginate` support for {Chewy::Search::Request}
5
+ # It is included automatically if `WillPaginate` is available.
6
+ #
7
+ # @example
8
+ # PlacesIndex.all.paginate(page: 3, per_page: 10).order(:name)
9
+ # # => <PlacesIndex::Query {..., :body=>{:size=>10, :from=>20, :sort=>["name"]}}>
10
+ module WillPaginate
11
+ extend ActiveSupport::Concern
12
+
13
+ included do
14
+ include ::WillPaginate::CollectionMethods
15
+ attr_reader :current_page, :per_page
16
+ end
17
+
18
+ def paginate(options = {})
19
+ @current_page = ::WillPaginate::PageNumber(options[:page] || @current_page || 1)
20
+ @page_multiplier = @current_page - 1
21
+ @per_page = (options[:per_page] || @per_page || ::WillPaginate.per_page).to_i
22
+
23
+ # call Chewy::Query methods to limit results
24
+ limit(@per_page).offset(@page_multiplier * @per_page)
25
+ end
26
+
27
+ def page(page)
28
+ paginate(page: page)
29
+ end
30
+
31
+ private
32
+
33
+ def paginated_collection(collection)
34
+ ::WillPaginate::Collection.create(current_page, per_page, total_entries) do |pager|
35
+ pager.replace collection
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,150 @@
1
+ Dir.glob(File.join(File.dirname(__FILE__), 'parameters', 'concerns', '*.rb')) { |f| require f }
2
+ Dir.glob(File.join(File.dirname(__FILE__), 'parameters', '*.rb')) { |f| require f }
3
+
4
+ module Chewy
5
+ module Search
6
+ # This class is basically a compound storage of the request
7
+ # parameter storages. It encapsulates some storage-collection-handling
8
+ # logic.
9
+ #
10
+ # @see Chewy::Search::Request#parameters
11
+ # @see Chewy::Search::Parameters::Storage
12
+ class Parameters
13
+ # Default storage classes warehouse. It is probably possible to
14
+ # add your own classes here if necessary, but I'm not sure it will work.
15
+ #
16
+ # @return [{Symbol => Chewy::Search::Parameters::Storage}]
17
+ def self.storages
18
+ @storages ||= Hash.new do |hash, name|
19
+ hash[name] = "Chewy::Search::Parameters::#{name.to_s.camelize}".constantize
20
+ end
21
+ end
22
+
23
+ # @return [{Symbol => Chewy::Search::Parameters::Storage}]
24
+ attr_accessor :storages
25
+ delegate :[], :[]=, to: :storages
26
+
27
+ # Accepts an initial hash as basic values or parameter storages.
28
+ #
29
+ # @example
30
+ # Chewy::Search::Parameters.new(limit: 10, offset 10)
31
+ # Chewy::Search::Parameters.new(
32
+ # limit: Chewy::Search::Parameters::Limit.new(10),
33
+ # limit: Chewy::Search::Parameters::Offset.new(10)
34
+ # )
35
+ # @param initial [{Symbol => Object, Chewy::Search::Parameters::Storage}]
36
+ def initialize(initial = {})
37
+ @storages = Hash.new do |hash, name|
38
+ hash[name] = self.class.storages[name].new
39
+ end
40
+ initial.each_with_object(@storages) do |(name, value), result|
41
+ storage_class = self.class.storages[name]
42
+ storage = value.is_a?(storage_class) ? value : storage_class.new(value)
43
+ result[name] = storage
44
+ end
45
+ end
46
+
47
+ # Compares storages by their values.
48
+ #
49
+ # @param other [Object] any object
50
+ # @return [true, false]
51
+ def ==(other)
52
+ super || other.is_a?(self.class) && compare_storages(other)
53
+ end
54
+
55
+ # Clones the specified storage, performs the operation
56
+ # defined by block on the clone.
57
+ #
58
+ # @param name [Symbol] parameter name
59
+ # @yield the block is executed in the cloned storage instance binding
60
+ # @return [Chewy::Search::Parameters::Storage]
61
+ def modify!(name, &block)
62
+ @storages[name] = @storages[name].clone.tap do |s|
63
+ s.instance_exec(&block)
64
+ end
65
+ end
66
+
67
+ # Removes specified storages from the storages hash.
68
+ #
69
+ # @param names [Array<String, Symbol>]
70
+ # @return [{Symbol => Chewy::Search::Parameters::Storage}] removed storages hash
71
+ def only!(names)
72
+ @storages.slice!(*assert_storages(names))
73
+ end
74
+
75
+ # Keeps only specified storages removing everything else.
76
+ #
77
+ # @param names [Array<String, Symbol>]
78
+ # @return [{Symbol => Chewy::Search::Parameters::Storage}] kept storages hash
79
+ def except!(names)
80
+ @storages.except!(*assert_storages(names))
81
+ end
82
+
83
+ # Takes all the storages and merges them one by one using
84
+ # {Chewy::Search::Parameters::Storage#merge!} method. Merging
85
+ # is implemented in different ways for different storages: for
86
+ # limit, offset and other single-value classes it is a simple
87
+ # value replacement, for boolean storages (explain, none) it uses
88
+ # a disjunction result, for compound values - merging and
89
+ # concatenation, for query, filter, post_filter - it is the
90
+ # "and" operation.
91
+ #
92
+ # @see Chewy::Search::Parameters::Storage#merge!
93
+ # @return [{Symbol => Chewy::Search::Parameters::Storage}] storages from other parameters
94
+ def merge!(other)
95
+ other.storages.each do |name, storage|
96
+ modify!(name) { merge!(storage) }
97
+ end
98
+ end
99
+
100
+ # Renders and merges all the parameter storages into a single hash.
101
+ #
102
+ # @return [Hash] request body
103
+ def render
104
+ body = @storages.except(:filter, :query, :none).values.inject({}) do |result, storage|
105
+ result.merge!(storage.render || {})
106
+ end
107
+ body.merge!(render_query || {})
108
+ body.present? ? {body: body} : {}
109
+ end
110
+
111
+ protected
112
+
113
+ def initialize_clone(origin)
114
+ @storages = origin.storages.clone
115
+ end
116
+
117
+ def compare_storages(other)
118
+ keys = (@storages.keys | other.storages.keys)
119
+ @storages.values_at(*keys) == other.storages.values_at(*keys)
120
+ end
121
+
122
+ def assert_storages(names)
123
+ raise ArgumentError, 'No storage names were specified' if names.empty?
124
+ names = names.map(&:to_sym)
125
+ self.class.storages.values_at(*names)
126
+ names
127
+ end
128
+
129
+ def render_query
130
+ none = @storages[:none].render
131
+
132
+ return none if none
133
+
134
+ filter = @storages[:filter].render
135
+ query = @storages[:query].render
136
+
137
+ return query unless filter
138
+
139
+ if query && query[:query][:bool]
140
+ query[:query][:bool].merge!(filter)
141
+ query
142
+ elsif query
143
+ {query: {bool: {must: query[:query]}.merge!(filter)}}
144
+ else
145
+ {query: {bool: filter}}
146
+ end
147
+ end
148
+ end
149
+ end
150
+ end