mongoid_fulltext 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/danger-comment.yml +19 -0
  3. data/.github/workflows/danger.yml +21 -0
  4. data/.github/workflows/lint.yml +29 -0
  5. data/.github/workflows/release.yml +30 -0
  6. data/.github/workflows/test.yml +81 -0
  7. data/.gitignore +2 -0
  8. data/.rubocop.yml +149 -3
  9. data/.rubocop_todo.yml +104 -59
  10. data/.spellcheck.txt +181 -0
  11. data/CHANGELOG.md +54 -33
  12. data/Dangerfile +5 -1
  13. data/Gemfile +22 -20
  14. data/Gemfile.danger +5 -0
  15. data/README.md +171 -178
  16. data/RELEASING.md +47 -30
  17. data/Rakefile +21 -3
  18. data/UPGRADING.md +43 -0
  19. data/lib/mongoid/full_text_search/field_scores.rb +48 -0
  20. data/lib/mongoid/full_text_search/index_definition.rb +31 -0
  21. data/lib/mongoid/full_text_search/ngrams.rb +93 -0
  22. data/lib/mongoid/full_text_search/version.rb +1 -1
  23. data/lib/mongoid/full_text_search.rb +94 -125
  24. data/mongoid_fulltext.gemspec +2 -3
  25. data/script/release.rb +13 -0
  26. data/spec/models/chinese_artwork.rb +7 -0
  27. data/spec/models/localized_artwork.rb +29 -0
  28. data/spec/models/multilingual_artwork.rb +7 -0
  29. data/spec/models/russian_artwork.rb +0 -1
  30. data/spec/models/scoped_artwork.rb +14 -0
  31. data/spec/models/tagged_artwork.rb +9 -0
  32. data/spec/models/weighted_artwork.rb +34 -0
  33. data/spec/mongoid/array_fields_spec.rb +43 -0
  34. data/spec/mongoid/bulk_indexing_spec.rb +56 -0
  35. data/spec/mongoid/candidate_limits_spec.rb +19 -0
  36. data/spec/mongoid/criteria_search_spec.rb +73 -0
  37. data/spec/mongoid/full_text_search_spec.rb +31 -6
  38. data/spec/mongoid/localized_fields_spec.rb +197 -0
  39. data/spec/mongoid/ngram_sampling_spec.rb +55 -0
  40. data/spec/mongoid/non_latin_spec.rb +50 -0
  41. data/spec/mongoid/timeout_option_spec.rb +18 -0
  42. data/spec/mongoid/weighted_fields_spec.rb +102 -0
  43. data/spec/release/release_spec.rb +60 -0
  44. data/spec/spec_helper.rb +15 -3
  45. data/spec/unit/field_scores_spec.rb +54 -0
  46. data/spec/unit/index_definition_spec.rb +48 -0
  47. data/spec/unit/ngrams_spec.rb +73 -0
  48. data/spec/version_spec.rb +7 -0
  49. metadata +41 -11
  50. data/.travis.yml +0 -33
@@ -7,8 +7,10 @@ else
7
7
  require 'mongoid/full_text_search/indexable'
8
8
  end
9
9
 
10
- require 'unicode_utils'
11
10
  require 'cgi'
11
+ require 'mongoid/full_text_search/ngrams'
12
+ require 'mongoid/full_text_search/index_definition'
13
+ require 'mongoid/full_text_search/field_scores'
12
14
 
13
15
  module Mongoid::FullTextSearch
14
16
  extend ActiveSupport::Concern
@@ -57,9 +59,13 @@ module Mongoid::FullTextSearch
57
59
 
58
60
  config.update(options)
59
61
 
62
+ raise ArgumentError, ':alphabet must be a String or Regexp' unless config[:alphabet].is_a?(String) || config[:alphabet].is_a?(Regexp)
63
+ raise ArgumentError, ':max_ngrams_to_search must be a positive integer' unless config[:max_ngrams_to_search].is_a?(Integer) && config[:max_ngrams_to_search] > 0
64
+
60
65
  args = [:to_s] if args.empty?
66
+ FieldScores.configure(config, args)
61
67
  config[:ngram_fields] = args
62
- config[:alphabet] = Hash[config[:alphabet].split('').map { |ch| [ch, ch] }]
68
+ config[:alphabet] = Hash[config[:alphabet].split('').map { |ch| [ch, ch] }] if config[:alphabet].is_a?(String)
63
69
  config[:word_separators] = Hash[config[:word_separators].split('').map { |ch| [ch, ch] }]
64
70
  mongoid_fulltext_config[index_name] = config
65
71
 
@@ -69,32 +75,48 @@ module Mongoid::FullTextSearch
69
75
 
70
76
  def create_fulltext_indexes
71
77
  return unless mongoid_fulltext_config
78
+
72
79
  mongoid_fulltext_config.each_pair do |index_name, fulltext_config|
73
80
  fulltext_search_ensure_indexes(index_name, fulltext_config)
74
81
  end
75
82
  end
76
83
 
84
+ def localized_fulltext_index?(config)
85
+ config[:ngram_fields].any? do |field_name|
86
+ field = fields[field_name.to_s]
87
+ field && field.localized?
88
+ end
89
+ end
90
+
91
+ def each_fulltext_index
92
+ mongoid_fulltext_config.each_pair do |index_name, config|
93
+ if localized_fulltext_index?(config)
94
+ I18n.available_locales.each do |locale|
95
+ I18n.with_locale(locale) { yield index_name, config, locale.to_s }
96
+ end
97
+ else
98
+ yield index_name, config, nil
99
+ end
100
+ end
101
+ end
102
+
77
103
  def fulltext_search_ensure_indexes(index_name, config)
78
104
  db = collection.database
79
105
  coll = db[index_name]
80
106
 
81
- # The order of filters matters when the same index is used from two or more collections.
82
- filter_indexes = (config[:filters] || []).map do |key, _value|
83
- ["filter_values.#{key}", 1]
84
- end.sort_by { |filter_index| filter_index[0] }
85
-
86
- index_definition = [['ngram', 1], ['score', -1]].concat(filter_indexes)
87
-
88
- # Since the definition of the index could have changed, we'll clean up by
89
- # removing any indexes that aren't on the exact.
90
- correct_keys = index_definition.map { |field_def| field_def[0] }
91
- all_filter_keys = filter_indexes.map { |field_def| field_def[0] }
92
- coll.indexes.each do |idef|
93
- keys = idef['key'].keys
94
- next unless keys.member?('ngram')
95
- all_filter_keys |= keys.find_all { |key| key.starts_with?('filter_values.') }
96
- next unless keys & correct_keys != correct_keys
97
- Mongoid.logger.info "Dropping #{idef['name']} [#{keys & correct_keys} <=> #{correct_keys}]" if Mongoid.logger
107
+ # Creating an index also creates the collection before older drivers list its indexes.
108
+ Mongoid.logger.info "Ensuring document_id index on #{coll.name}" if Mongoid.logger
109
+ if Mongoid::Compatibility::Version.mongoid5_or_newer?
110
+ coll.indexes.create_one('document_id' => 1)
111
+ else
112
+ coll.indexes.create('document_id' => 1)
113
+ end
114
+
115
+ existing_indexes = []
116
+ coll.indexes.each { |index| existing_indexes << index }
117
+ definition = IndexDefinition.new(config[:filters], localized_fulltext_index?(config), existing_indexes)
118
+ definition.obsolete_indexes.each do |idef|
119
+ Mongoid.logger.info "Dropping #{idef['name']} [#{idef['key'].keys} <=> #{definition.keys.map(&:first)}]" if Mongoid.logger
98
120
  if Mongoid::Compatibility::Version.mongoid5_or_newer?
99
121
  coll.indexes.drop_one(idef['key'])
100
122
  else
@@ -102,24 +124,13 @@ module Mongoid::FullTextSearch
102
124
  end
103
125
  end
104
126
 
105
- if all_filter_keys.length > filter_indexes.length
106
- filter_indexes = all_filter_keys.map { |key| [key, 1] }.sort_by { |filter_index| filter_index[0] }
107
- index_definition = [['ngram', 1], ['score', -1]].concat(filter_indexes)
108
- end
109
-
127
+ index_definition = definition.keys
110
128
  Mongoid.logger.info "Ensuring fts_index on #{coll.name}: #{index_definition}" if Mongoid.logger
111
129
  if Mongoid::Compatibility::Version.mongoid5_or_newer?
112
130
  coll.indexes.create_one(Hash[index_definition], name: 'fts_index')
113
131
  else
114
132
  coll.indexes.create(Hash[index_definition], name: 'fts_index')
115
133
  end
116
-
117
- Mongoid.logger.info "Ensuring document_id index on #{coll.name}" if Mongoid.logger
118
- if Mongoid::Compatibility::Version.mongoid5_or_newer?
119
- coll.indexes.create_one('document_id' => 1) # to make removes fast
120
- else
121
- coll.indexes.create('document_id' => 1) # to make removes fast
122
- end
123
134
  end
124
135
 
125
136
  def fulltext_search(query_string, options = {})
@@ -140,9 +151,12 @@ module Mongoid::FullTextSearch
140
151
  # get a count of the number of index documents containing that n-gram
141
152
  ordering = { 'score' => -1 }
142
153
  limit = mongoid_fulltext_config[index_name][:max_candidate_set_size]
154
+ config = mongoid_fulltext_config[index_name]
143
155
  coll = collection.database[index_name]
144
156
  cursors = ngrams.map do |ngram|
145
157
  query = { 'ngram' => ngram[0] }
158
+ query['locale'] = I18n.locale.to_s if localized_fulltext_index?(config)
159
+ query.update(document_type_filters)
146
160
  query.update(map_query_filters(options))
147
161
  count = coll.find(query).count
148
162
  { ngram: ngram, count: count, query: query }
@@ -156,6 +170,7 @@ module Mongoid::FullTextSearch
156
170
  results_so_far = 0
157
171
  candidates_list = cursors.map do |doc|
158
172
  next if doc[:count] == 0
173
+
159
174
  query_result = coll.find(doc[:query])
160
175
  if results_so_far >= limit
161
176
  query_result = query_result.sort(ordering).limit(max_results)
@@ -187,95 +202,32 @@ module Mongoid::FullTextSearch
187
202
  all_scores.concat(scores)
188
203
  end
189
204
  all_scores.sort! { |document1, document2| -document1[:score] <=> -document2[:score] }
190
- instantiate_mapreduce_results(all_scores[0..max_results - 1], return_scores: return_scores)
205
+ if max_results > 0
206
+ instantiate_mapreduce_results(all_scores, return_scores: return_scores, max_results: max_results)
207
+ else
208
+ instantiate_mapreduce_results(all_scores[0..max_results - 1], return_scores: return_scores)
209
+ end
191
210
  end
192
211
 
193
212
  def instantiate_mapreduce_result(result)
194
- result[:clazz].constantize.find(result[:id])
213
+ scope = criteria
214
+ scope = result[:clazz].constantize.criteria if scope.selector.empty?
215
+ # Mongoid 7.0 and older replace an existing _id condition with where; and keeps both.
216
+ scope.and(_id: result[:id]).first
195
217
  end
196
218
 
197
219
  def instantiate_mapreduce_results(results, options)
198
- if options[:return_scores]
199
- results.map { |result| [instantiate_mapreduce_result(result), result[:score]] }.find_all { |result| !result[0].nil? }
200
- else
201
- results.map { |result| instantiate_mapreduce_result(result) }.compact
220
+ results.each_with_object([]) do |result, documents|
221
+ document = instantiate_mapreduce_result(result)
222
+ next unless document
223
+
224
+ documents << (options[:return_scores] ? [document, result[:score]] : document)
225
+ break documents if options[:max_results] && documents.length >= options[:max_results]
202
226
  end
203
227
  end
204
228
 
205
229
  def all_ngrams(str, config, bound_number_returned = true)
206
- return {} if str.nil?
207
-
208
- if config[:remove_accents]
209
- if defined?(UnicodeUtils)
210
- str = UnicodeUtils.nfkd(str)
211
- elsif defined?(DiacriticsFu)
212
- str = DiacriticsFu.escape(str)
213
- end
214
- end
215
-
216
- # Remove any characters that aren't in the alphabet and aren't word separators
217
- filtered_str = str.mb_chars.downcase.to_s.split('').find_all { |ch| config[:alphabet][ch] || config[:word_separators][ch] }.join('')
218
-
219
- # Figure out how many ngrams to extract from the string. If we can't afford to extract all ngrams,
220
- # step over the string in evenly spaced strides to extract ngrams. For example, to extract 3 3-letter
221
- # ngrams from 'abcdefghijk', we'd want to extract 'abc', 'efg', and 'ijk'.
222
- step_size = if bound_number_returned
223
- [((filtered_str.length - config[:ngram_width]).to_f / config[:max_ngrams_to_search]).ceil, 1].max
224
- else
225
- 1
226
- end
227
-
228
- # Create an array of records of the form {:ngram => x, :score => y} for all ngrams that occur in the
229
- # input string using the step size that we just computed. Let score(x,y) be the score of string x
230
- # compared with string y - assigning scores to ngrams with the square root-based scoring function
231
- # below and multiplying scores of matching ngrams together yields a score function that has the
232
- # property that score(x,y) > score(x,z) for any string z containing y and score(x,y) > score(x,z)
233
- # for any string z contained in y.
234
- ngram_array = (0..filtered_str.length - config[:ngram_width]).step(step_size).map do |i|
235
- score = if i == 0 || (config[:apply_prefix_scoring_to_all_words] && \
236
- config[:word_separators].key?(filtered_str[i - 1].chr))
237
- Math.sqrt(1 + 1.0 / filtered_str.length)
238
- else
239
- Math.sqrt(2.0 / filtered_str.length)
240
- end
241
- { ngram: filtered_str[i..i + config[:ngram_width] - 1], score: score }
242
- end
243
-
244
- # If an ngram appears multiple times in the query string, keep the max score
245
- ngram_array = ngram_array.group_by { |h| h[:ngram] }.map { |key, values| { ngram: key, score: values.map { |v| v[:score] }.max } }
246
-
247
- if config[:index_short_prefixes] || config[:index_full_words]
248
- split_regex_def = config[:word_separators].keys.map { |k| Regexp.escape(k) }.join
249
- split_regex = Regexp.compile("[#{split_regex_def}]")
250
- all_words = filtered_str.split(split_regex)
251
- end
252
-
253
- # Add 'short prefix' records to the array: prefixes of the string that are length (ngram_width - 1)
254
- if config[:index_short_prefixes]
255
- prefixes_seen = {}
256
- all_words.each do |word|
257
- next if word.length < config[:ngram_width] - 1
258
- prefix = word[0...config[:ngram_width] - 1]
259
- if prefixes_seen[prefix].nil? && (config[:stop_words][word].nil? || word == filtered_str)
260
- ngram_array << { ngram: prefix, score: 1 + 1.0 / filtered_str.length }
261
- prefixes_seen[prefix] = true
262
- end
263
- end
264
- end
265
-
266
- # Add records to the array of ngrams for each full word in the string that isn't a stop word
267
- if config[:index_full_words]
268
- full_words_seen = {}
269
- all_words.each do |word|
270
- if word.length > 1 && full_words_seen[word].nil? && (config[:stop_words][word].nil? || word == filtered_str)
271
- ngram_array << { ngram: word, score: 1 + 1.0 / filtered_str.length }
272
- full_words_seen[word] = true
273
- end
274
- end
275
- end
276
-
277
- # If an ngram appears as any combination of full word, short prefix, and ngram, keep the sum of the two scores
278
- Hash[ngram_array.group_by { |h| h[:ngram] }.map { |key, values| [key, values.map { |v| v[:score] }.sum] }]
230
+ Ngrams.calculate(str, config, bound_number_returned)
279
231
  end
280
232
 
281
233
  def remove_from_ngram_index
@@ -289,18 +241,26 @@ module Mongoid::FullTextSearch
289
241
  end
290
242
  end
291
243
 
292
- def update_ngram_index
293
- all.each(&:update_ngram_index)
244
+ def update_ngram_index(options = { timeout: true })
245
+ items = all
246
+ items = items.no_timeout if options.key?(:timeout) && !options[:timeout]
247
+ items.each(&:update_ngram_index)
294
248
  end
295
249
 
296
250
  private
297
251
 
252
+ def document_type_filters
253
+ return {} if criteria.selector.empty? && descendants.empty? && !superclass.respond_to?(:mongoid_fulltext_config)
254
+
255
+ { 'class' => { '$in' => ([self] + descendants).map(&:name) } }
256
+ end
257
+
298
258
  # Take a list of filters to be mapped so they can update the query
299
259
  # used upon the fulltext search of the ngrams
300
260
  def map_query_filters(filters)
301
261
  Hash[filters.map do |key, value|
302
262
  case value
303
- when Hash then
263
+ when Hash
304
264
  if value.key? :any then format_query_filter('$in', key, value[:any])
305
265
  elsif value.key? :all then format_query_filter('$all', key, value[:all])
306
266
  else raise UnknownFilterQueryOperator, value.keys.join(','), caller end
@@ -315,7 +275,7 @@ module Mongoid::FullTextSearch
315
275
  end
316
276
 
317
277
  def update_ngram_index
318
- mongoid_fulltext_config.each_pair do |index_name, fulltext_config|
278
+ self.class.each_fulltext_index do |index_name, fulltext_config, locale|
319
279
  if condition = fulltext_config[:update_if]
320
280
  case condition
321
281
  when Symbol then next unless send condition
@@ -327,15 +287,22 @@ module Mongoid::FullTextSearch
327
287
 
328
288
  # remove existing ngrams from external index
329
289
  coll = collection.database[index_name.to_sym]
290
+ removal_query = { 'document_id' => _id }
291
+ removal_query['locale'] = locale if locale
330
292
  if Mongoid::Compatibility::Version.mongoid5_or_newer?
331
- coll.find('document_id' => _id).delete_many
293
+ coll.find(removal_query).delete_many
332
294
  else
333
- coll.find('document_id' => _id).remove_all
295
+ coll.find(removal_query).remove_all
334
296
  end
335
297
  # extract ngrams from fields
336
- field_values = fulltext_config[:ngram_fields].map { |field| send(field) }
337
- ngrams = field_values.inject({}) { |accum, item| accum.update(self.class.all_ngrams(item, fulltext_config, false)) }
338
- return if ngrams.empty?
298
+ ngrams = if fulltext_config.key?(:priorities)
299
+ FieldScores.calculate(fulltext_config) { |field| send(field) }
300
+ else
301
+ field_values = fulltext_config[:ngram_fields].flat_map { |field| send(field) }
302
+ field_values.inject({}) { |accum, item| accum.update(self.class.all_ngrams(item, fulltext_config, false)) }
303
+ end
304
+ next if ngrams.empty?
305
+
339
306
  # apply filters, if necessary
340
307
  filter_values = nil
341
308
  if fulltext_config.key?(:filters)
@@ -348,14 +315,16 @@ module Mongoid::FullTextSearch
348
315
  end.compact]
349
316
  end
350
317
  # insert new ngrams in external index
351
- ngrams.each_pair do |ngram, score|
318
+ index_documents = ngrams.map do |ngram, score|
352
319
  index_document = { 'ngram' => ngram, 'document_id' => _id, 'score' => score, 'class' => self.class.name }
320
+ index_document['locale'] = locale if locale
353
321
  index_document['filter_values'] = filter_values if fulltext_config.key?(:filters)
354
- if Mongoid::Compatibility::Version.mongoid5_or_newer?
355
- coll.insert_one(index_document)
356
- else
357
- coll.insert(index_document)
358
- end
322
+ index_document
323
+ end
324
+ if Mongoid::Compatibility::Version.mongoid5_or_newer?
325
+ coll.insert_many(index_documents)
326
+ else
327
+ coll.insert(index_documents)
359
328
  end
360
329
  end
361
330
  end
@@ -1,5 +1,4 @@
1
- $LOAD_PATH.push File.expand_path('lib', __dir__)
2
- require 'mongoid/full_text_search/version'
1
+ require_relative 'lib/mongoid/full_text_search/version'
3
2
 
4
3
  Gem::Specification.new do |s|
5
4
  s.name = 'mongoid_fulltext'
@@ -13,7 +12,7 @@ Gem::Specification.new do |s|
13
12
  s.homepage = 'https://github.com/mongoid/mongoid_fulltext'
14
13
  s.licenses = ['MIT']
15
14
  s.summary = 'Full-text search for the Mongoid ORM, using n-grams extracted from text.'
16
- s.add_dependency 'mongoid', '>= 3.0', '< 8'
15
+ s.add_dependency 'mongoid', '>= 3.0', '< 10'
17
16
  s.add_dependency 'mongoid-compatibility', '>= 0.5.1'
18
17
  s.add_dependency 'unicode_utils'
19
18
  s.add_development_dependency 'database_cleaner'
data/script/release.rb ADDED
@@ -0,0 +1,13 @@
1
+ require 'ruby-gem-release/changelog'
2
+ require 'ruby-gem-release/workflow/ruby_gem'
3
+
4
+ # Builds the ruby-gem-release workflow used by the Rakefile, the Release GitHub Actions workflow, and spec/release.
5
+ module MongoidFulltextRelease
6
+ def self.workflow(**options)
7
+ RubyGemRelease::Workflow::RubyGem.new(
8
+ version: RubyGemRelease::Version::RubyConstant.new(path: 'lib/mongoid/full_text_search/version.rb', constant: 'VERSION'),
9
+ changelog: RubyGemRelease::Changelog::Intridea.new(placeholder: '* Your contribution here.'),
10
+ **options
11
+ )
12
+ end
13
+ end
@@ -0,0 +1,7 @@
1
+ class ChineseArtwork
2
+ include Mongoid::Document
3
+ include Mongoid::FullTextSearch
4
+
5
+ field :title, type: String
6
+ fulltext_search_in :title, alphabet: /\p{Han}/, ngram_width: 2
7
+ end
@@ -0,0 +1,29 @@
1
+ class LocalizedArtwork
2
+ include Mongoid::Document
3
+ include Mongoid::FullTextSearch
4
+
5
+ field :title, type: String, localize: true
6
+ field :artist, type: String
7
+ fulltext_search_in :title, :artist, :description, filters: { language: ->(_document) { I18n.locale.to_s } }
8
+
9
+ def description
10
+ I18n.locale == :cs ? 'Cesky' : 'English'
11
+ end
12
+ end
13
+
14
+ class PartlyLocalizedArtwork
15
+ include Mongoid::Document
16
+ include Mongoid::FullTextSearch
17
+
18
+ field :title, type: String, localize: true
19
+ field :artist, type: String
20
+ fulltext_search_in :artist, index_name: 'mongoid_fulltext.untranslated'
21
+ end
22
+
23
+ class OnlyLocalizedArtwork
24
+ include Mongoid::Document
25
+ include Mongoid::FullTextSearch
26
+
27
+ field :title, type: String, localize: true
28
+ fulltext_search_in :title
29
+ end
@@ -0,0 +1,7 @@
1
+ class MultilingualArtwork
2
+ include Mongoid::Document
3
+ include Mongoid::FullTextSearch
4
+
5
+ field :title, type: String
6
+ fulltext_search_in :title, alphabet: /[\p{L}\p{M}\p{N}]/, ngram_width: 2, remove_accents: false
7
+ end
@@ -1,4 +1,3 @@
1
-
2
1
  class RussianArtwork
3
2
  include Mongoid::Document
4
3
  include Mongoid::FullTextSearch
@@ -0,0 +1,14 @@
1
+ class ScopedArtwork
2
+ include Mongoid::Document
3
+ include Mongoid::FullTextSearch
4
+
5
+ field :title, type: String
6
+ field :value, type: Integer
7
+ fulltext_search_in :title
8
+ end
9
+
10
+ class InheritedArtwork < ScopedArtwork
11
+ end
12
+
13
+ class FurtherInheritedArtwork < InheritedArtwork
14
+ end
@@ -0,0 +1,9 @@
1
+ class TaggedArtwork
2
+ include Mongoid::Document
3
+ include Mongoid::FullTextSearch
4
+
5
+ field :title, type: String
6
+ field :tags, type: Array
7
+
8
+ fulltext_search_in :title, :tags
9
+ end
@@ -0,0 +1,34 @@
1
+ class WeightedArtwork
2
+ include Mongoid::Document
3
+ include Mongoid::FullTextSearch
4
+
5
+ field :title, type: String
6
+ field :description, type: String
7
+ field :tags, type: Array
8
+ fulltext_search_in :title, :description, :tags, index_name: 'weighted_max',
9
+ priorities: { title: 10, 'description' => 5 }
10
+ fulltext_search_in :tags, :description, :title, index_name: 'weighted_sum',
11
+ priorities: { title: 10, description: 5 }, score_aggregation: :sum
12
+ end
13
+
14
+ class WeightedComputedArtwork
15
+ include Mongoid::Document
16
+ include Mongoid::FullTextSearch
17
+
18
+ field :title, type: String
19
+ fulltext_search_in :title, :search_text, priorities: { search_text: 2.5 }, score_aggregation: :sum
20
+
21
+ def search_text
22
+ title
23
+ end
24
+ end
25
+
26
+ class WeightedLocalizedArtwork
27
+ include Mongoid::Document
28
+ include Mongoid::FullTextSearch
29
+
30
+ field :title, type: String, localize: true
31
+ field :description, type: String
32
+ fulltext_search_in :title, :description, priorities: { title: 10 },
33
+ filters: { language: ->(_document) { I18n.locale.to_s } }
34
+ end
@@ -0,0 +1,43 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Array fields' do
4
+ it 'searches each tag as well as scalar fields' do
5
+ artwork = TaggedArtwork.create!(title: 'Painting', tags: %w[ghost accounting])
6
+ %w[painting ghost accounting].each do |query|
7
+ expect(TaggedArtwork.fulltext_search(query)).to eq([artwork])
8
+ end
9
+ end
10
+
11
+ it 'does not create ngrams across array element boundaries' do
12
+ artwork = TaggedArtwork.create!(tags: %w[ab cd])
13
+ config = TaggedArtwork.mongoid_fulltext_config.values.first
14
+ coll = artwork.collection.database[TaggedArtwork.mongoid_fulltext_config.keys.first]
15
+ expected = %w[ab cd].inject({}) do |ngrams, tag|
16
+ ngrams.update(TaggedArtwork.all_ngrams(tag, config, false))
17
+ end
18
+ actual = Hash[coll.find.map { |document| [document['ngram'], document['score']] }]
19
+ expect(actual).to eq(expected)
20
+ end
21
+
22
+ it 'handles nil, empty, and repeated elements without duplicate records' do
23
+ artwork = TaggedArtwork.create!(tags: [nil, '', 'ghost', 'ghost'])
24
+ expect(TaggedArtwork.fulltext_search('ghost')).to eq([artwork])
25
+ coll = artwork.collection.database[TaggedArtwork.mongoid_fulltext_config.keys.first]
26
+ ngrams = coll.find.map { |document| document['ngram'] }
27
+ expect(ngrams).to eq(ngrams.uniq)
28
+ end
29
+
30
+ it 'removes old tags when the array changes or becomes empty' do
31
+ artwork = TaggedArtwork.create!(tags: ['ghost'])
32
+ artwork.update_attributes!(tags: ['accounting'])
33
+ expect(TaggedArtwork.fulltext_search('ghost')).to eq([])
34
+ expect(TaggedArtwork.fulltext_search('accounting')).to eq([artwork])
35
+ artwork.update_attributes!(tags: [])
36
+ expect(TaggedArtwork.fulltext_search('accounting')).to eq([])
37
+ end
38
+
39
+ it 'still indexes scalar fields when the array is nil' do
40
+ artwork = TaggedArtwork.create!(title: 'Painting', tags: nil)
41
+ expect(TaggedArtwork.fulltext_search('painting')).to eq([artwork])
42
+ end
43
+ end
@@ -0,0 +1,56 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Bulk ngram indexing' do
4
+ let(:artwork) { BasicArtwork.new(title: 'A long title with many searchable ngrams') }
5
+ let(:index_name) { BasicArtwork.mongoid_fulltext_config.keys.first }
6
+ let(:config) { BasicArtwork.mongoid_fulltext_config[index_name] }
7
+ let(:collection) { artwork.collection }
8
+ let(:database) { collection.database }
9
+ let(:index) { database[index_name] }
10
+
11
+ before do
12
+ allow(artwork).to receive(:collection).and_return(collection)
13
+ allow(collection).to receive(:database).and_return(database)
14
+ allow(database).to receive(:[]).and_call_original
15
+ allow(database).to receive(:[]).with(index_name.to_sym).and_return(index)
16
+ end
17
+
18
+ it 'inserts all ngrams with one driver call and preserves their scores' do
19
+ documents = BasicArtwork.all_ngrams(artwork.title, config, false).map do |ngram, score|
20
+ { 'ngram' => ngram, 'document_id' => artwork.id, 'score' => score, 'class' => 'BasicArtwork' }
21
+ end
22
+ expect(documents.length).to be > 10
23
+ method = Mongoid::Compatibility::Version.mongoid5_or_newer? ? :insert_many : :insert
24
+ expect(index).to receive(method).with(documents).once.and_call_original
25
+ artwork.save!
26
+ expect(BasicArtwork.fulltext_search(artwork.title)).to eq([artwork])
27
+ end
28
+
29
+ it 'does not call insert for an empty ngram set' do
30
+ artwork.title = ''
31
+ expect(index).not_to receive(:insert_many)
32
+ expect(index).not_to receive(:insert)
33
+ artwork.update_ngram_index
34
+ expect(index.find.count).to eq(0)
35
+ end
36
+
37
+ it 'replaces previous records rather than accumulating duplicates' do
38
+ artwork.save!
39
+ artwork.update_attributes!(title: 'Replacement')
40
+ expect(BasicArtwork.fulltext_search('searchable')).to eq([])
41
+ expect(BasicArtwork.fulltext_search('replacement')).to eq([artwork])
42
+ expect(index.find.count).to eq(BasicArtwork.all_ngrams('Replacement', config, false).length)
43
+ end
44
+
45
+ it 'continues indexing other fields when an earlier index is empty' do
46
+ artwork = MultiExternalArtwork.create!(title: '', year: '1970', artist: 'Picasso')
47
+ expect(MultiExternalArtwork.fulltext_search('1970', index: 'mongoid_fulltext.years')).to eq([artwork])
48
+ expect(MultiExternalArtwork.fulltext_search('Picasso', index: 'mongoid_fulltext.all')).to eq([artwork])
49
+ end
50
+
51
+ it 'retains filter values for all inserted ngrams' do
52
+ artwork = FilteredArtwork.create!(title: 'Flowers')
53
+ expect(FilteredArtwork.fulltext_search('flowers', is_artwork: true)).to eq([artwork])
54
+ expect(FilteredArtwork.fulltext_search('flowers', is_artwork: false)).to eq([])
55
+ end
56
+ end
@@ -0,0 +1,19 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Full-text candidate limits' do
4
+ it 'bounds initial candidates and continues with limited candidates for later ngrams' do
5
+ config = BasicArtwork.mongoid_fulltext_config.values.first
6
+ original = config[:max_candidate_set_size]
7
+ begin
8
+ config[:max_candidate_set_size] = 1
9
+ artworks = 2.times.map { BasicArtwork.create!(title: 'alphabet beta') }
10
+
11
+ results = BasicArtwork.fulltext_search('alphabet beta', max_results: 1, return_scores: true)
12
+ expect(results.length).to eq(1)
13
+ expect(artworks).to include(results.first.first)
14
+ expect(results.first.last).to be > 0
15
+ ensure
16
+ config[:max_candidate_set_size] = original
17
+ end
18
+ end
19
+ end