mongoid_fulltext 0.8.0 → 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.
- checksums.yaml +5 -5
- data/.github/workflows/danger-comment.yml +19 -0
- data/.github/workflows/danger.yml +21 -0
- data/.github/workflows/lint.yml +29 -0
- data/.github/workflows/release.yml +30 -0
- data/.github/workflows/test.yml +81 -0
- data/.gitignore +2 -0
- data/.rubocop.yml +149 -3
- data/.rubocop_todo.yml +131 -51
- data/.spellcheck.txt +181 -0
- data/CHANGELOG.md +57 -31
- data/Dangerfile +5 -1
- data/Gemfile +22 -18
- data/Gemfile.danger +5 -0
- data/README.md +171 -179
- data/RELEASING.md +60 -0
- data/Rakefile +21 -3
- data/UPGRADING.md +43 -0
- data/lib/mongoid/full_text_search/field_scores.rb +48 -0
- data/lib/mongoid/full_text_search/index_definition.rb +31 -0
- data/lib/mongoid/full_text_search/indexable.rb +1 -1
- data/lib/mongoid/full_text_search/indexes.rb +1 -1
- data/lib/mongoid/full_text_search/ngrams.rb +93 -0
- data/lib/mongoid/full_text_search/version.rb +1 -1
- data/lib/mongoid/full_text_search.rb +112 -144
- data/mongoid_fulltext.gemspec +4 -4
- data/script/release.rb +13 -0
- data/spec/models/chinese_artwork.rb +7 -0
- data/spec/models/filtered_artist.rb +1 -2
- data/spec/models/filtered_artwork.rb +1 -2
- data/spec/models/filtered_other.rb +1 -2
- data/spec/models/localized_artwork.rb +29 -0
- data/spec/models/multilingual_artwork.rb +7 -0
- data/spec/models/partitioned_artist.rb +1 -1
- data/spec/models/russian_artwork.rb +1 -2
- data/spec/models/scoped_artwork.rb +14 -0
- data/spec/models/tagged_artwork.rb +9 -0
- data/spec/models/weighted_artwork.rb +34 -0
- data/spec/mongoid/array_fields_spec.rb +43 -0
- data/spec/mongoid/bulk_indexing_spec.rb +56 -0
- data/spec/mongoid/candidate_limits_spec.rb +19 -0
- data/spec/mongoid/criteria_search_spec.rb +73 -0
- data/spec/mongoid/full_text_search_spec.rb +41 -12
- data/spec/mongoid/localized_fields_spec.rb +197 -0
- data/spec/mongoid/ngram_sampling_spec.rb +55 -0
- data/spec/mongoid/non_latin_spec.rb +50 -0
- data/spec/mongoid/timeout_option_spec.rb +18 -0
- data/spec/mongoid/weighted_fields_spec.rb +102 -0
- data/spec/release/release_spec.rb +60 -0
- data/spec/spec_helper.rb +22 -7
- data/spec/support/mongoid.rb +6 -4
- data/spec/unit/field_scores_spec.rb +54 -0
- data/spec/unit/index_definition_spec.rb +48 -0
- data/spec/unit/ngrams_spec.rb +73 -0
- data/spec/version_spec.rb +7 -0
- metadata +62 -11
- data/.travis.yml +0 -30
data/Rakefile
CHANGED
|
@@ -3,6 +3,17 @@ require 'bundler/gem_tasks'
|
|
|
3
3
|
|
|
4
4
|
Bundler.setup :default, :development
|
|
5
5
|
|
|
6
|
+
if RUBY_ENGINE == 'ruby' && Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.3')
|
|
7
|
+
require_relative 'script/release'
|
|
8
|
+
MongoidFulltextRelease.workflow.install_tasks
|
|
9
|
+
|
|
10
|
+
%w[release release:rubygem_push release:source_control_push].each do |name|
|
|
11
|
+
Rake::Task[name].clear
|
|
12
|
+
desc 'Disabled; releases run through GitHub Actions, see RELEASING.md'
|
|
13
|
+
task(name) { abort "#{name} is disabled; releases run through GitHub Actions, see RELEASING.md" }
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
|
|
6
17
|
require 'rspec/core'
|
|
7
18
|
require 'rspec/core/rake_task'
|
|
8
19
|
|
|
@@ -10,7 +21,14 @@ RSpec::Core::RakeTask.new(:spec) do |spec|
|
|
|
10
21
|
spec.pattern = FileList['spec/**/*_spec.rb']
|
|
11
22
|
end
|
|
12
23
|
|
|
13
|
-
|
|
14
|
-
|
|
24
|
+
lint = RUBY_ENGINE == 'ruby' && Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.3') &&
|
|
25
|
+
Gem.loaded_specs.key?('rubocop')
|
|
26
|
+
if lint
|
|
27
|
+
require 'rubocop/rake_task'
|
|
28
|
+
RuboCop::RakeTask.new(:rubocop)
|
|
29
|
+
|
|
30
|
+
desc 'Lint Ruby, Markdown, YAML, and spelling'
|
|
31
|
+
task lint: :rubocop
|
|
32
|
+
end
|
|
15
33
|
|
|
16
|
-
task default: [
|
|
34
|
+
task default: lint ? %i[rubocop spec] : %i[spec]
|
data/UPGRADING.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Upgrading
|
|
2
|
+
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Weighted Fields
|
|
6
|
+
|
|
7
|
+
`:priorities` and `:score_aggregation` are opt-in. Indexes declaring neither option retain the existing last-field-wins behavior and exact scores, and require no rebuild. Opted-in indexes use maximum per-field array contributions followed by either maximum or summed weighted field contributions. Even `:priorities => {}` or `:score_aggregation => :max` intentionally switches from legacy merging to maximum scoring.
|
|
8
|
+
|
|
9
|
+
After enabling either option, changing weights, or changing aggregation, rebuild every affected model:
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
Artwork.update_ngram_index(timeout: false)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This replaces each document's stored scores, including all configured locales. No collection format or database-index change is required. For shared collections, rebuild every model whose configuration changed. Coordinate writes and searches during rebuilding: until it finishes, results mix old and new scores. Rebuild from a stable dataset or pause affected writes to avoid races with normal save callbacks.
|
|
16
|
+
|
|
17
|
+
Remove neither option without rebuilding again: unweighted declarations will only restore legacy scores as documents are subsequently reindexed. Review result ordering, score thresholds, and candidate limits when adopting weights or sum aggregation; the unweighted prefix/full-word scoring thresholds do not apply to weighted/summed scores.
|
|
18
|
+
|
|
19
|
+
### Query Ngram Sampling
|
|
20
|
+
|
|
21
|
+
Query sampling now respects `max_ngrams_to_search` and spans both ends of the query when selecting at least two sliding-window ngrams. For example, selecting three 3-character ngrams from `abcdefghijk` previously produced `abc`, `def`, and `ghi`; it now produces `abc`, `efg`, and `ijk`. A limit of one selects the first window. Full-word and short-prefix terms are added separately and can increase the total number of queried terms.
|
|
22
|
+
|
|
23
|
+
The same query can return different matches or a different result order because scores are calculated from a different selection of query fragments. Review any application expectations that depend on exact matches, rankings, or score thresholds. No index rebuild is needed for this sampling change: document indexes already store every ngram, and only query-time selection changes.
|
|
24
|
+
|
|
25
|
+
### Localized Fields
|
|
26
|
+
|
|
27
|
+
Indexes that explicitly include a Mongoid localized field now store ngrams for all configured locales in the original index collection, distinguished by a string `locale` field. Previously only the active translation was indexed, without locale metadata. Searches now filter by locale, and the compound search index begins with `locale`, `ngram`, and `score`. Nonlocalized indexes are unchanged.
|
|
28
|
+
|
|
29
|
+
Only models whose full-text index explicitly includes a localized field need this migration. Existing nonlocalized indexes require no changes.
|
|
30
|
+
|
|
31
|
+
Configure `I18n.available_locales` before using the model. For every affected model, run:
|
|
32
|
+
|
|
33
|
+
```ruby
|
|
34
|
+
Artwork.remove_from_ngram_index
|
|
35
|
+
Artwork.create_indexes
|
|
36
|
+
Artwork.update_ngram_index(timeout: false)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`remove_from_ngram_index` clears that model's old untagged records. `create_indexes` replaces the old compound search index with the locale-prefixed definition; there is no need to drop the collection or manually drop its indexes. `update_ngram_index` rebuilds the ngrams for all configured locales. Running only `create_indexes` does not migrate existing records: searches now require locale metadata, which old records lack. For a shared index, migrate every participating model.
|
|
40
|
+
|
|
41
|
+
Pause affected searches and writes while clearing and rebuilding, and resume after verifying searches in every locale. Searches will be incomplete during rebuilding. Searches use the current `I18n.locale`, and field access honors Mongoid's configured translation fallbacks.
|
|
42
|
+
|
|
43
|
+
Rebuild after adding a locale. Removing a locale from `I18n.available_locales` does not automatically purge its existing records on save; clear and rebuild the model's index to remove them. Document removal, destruction, and class-level removal delete records across all locales, including locales no longer configured. All models sharing a localized index must declare a localized field in that index and use the same locale configuration. No locale-suffixed collections are created.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
module Mongoid
|
|
2
|
+
module FullTextSearch
|
|
3
|
+
# Combines weighted field contributions without counting duplicate array elements.
|
|
4
|
+
module FieldScores
|
|
5
|
+
module_function
|
|
6
|
+
|
|
7
|
+
def configure(config, fields)
|
|
8
|
+
return unless config.key?(:priorities) || config.key?(:score_aggregation)
|
|
9
|
+
|
|
10
|
+
priorities = config.fetch(:priorities, {})
|
|
11
|
+
raise ArgumentError, ':priorities must be a Hash' unless priorities.is_a?(Hash)
|
|
12
|
+
|
|
13
|
+
normalized = {}
|
|
14
|
+
priorities.each do |field, weight|
|
|
15
|
+
raise ArgumentError, ':priorities keys must name indexed fields' unless (field.is_a?(String) || field.is_a?(Symbol)) && fields.map(&:to_s).include?(field.to_s)
|
|
16
|
+
raise ArgumentError, ':priorities values must be positive finite numbers' unless weight.is_a?(Numeric) && weight.real? && weight.to_f.finite? && weight.to_f > 0
|
|
17
|
+
raise ArgumentError, ':priorities contains duplicate field names' if normalized.key?(field.to_s)
|
|
18
|
+
|
|
19
|
+
normalized[field.to_s] = weight.to_f
|
|
20
|
+
end
|
|
21
|
+
aggregation = config.fetch(:score_aggregation, :max)
|
|
22
|
+
raise ArgumentError, ':score_aggregation must be :max or :sum' unless %i[max sum].include?(aggregation)
|
|
23
|
+
|
|
24
|
+
config[:priorities] = normalized
|
|
25
|
+
config[:score_aggregation] = aggregation
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def calculate(config)
|
|
29
|
+
config[:ngram_fields].map(&:to_s).uniq.each_with_object({}) do |field, scores|
|
|
30
|
+
field_scores = [yield(field)].flatten(1).inject({}) do |terms, value|
|
|
31
|
+
terms.merge(Ngrams.calculate(value, config, false)) { |_term, first, second| [first, second].max }
|
|
32
|
+
end
|
|
33
|
+
weight = config[:priorities].fetch(field.to_s, 1.0)
|
|
34
|
+
field_scores.each do |term, score|
|
|
35
|
+
weighted = score * weight
|
|
36
|
+
scores[term] = if !scores.key?(term)
|
|
37
|
+
weighted
|
|
38
|
+
elsif config[:score_aggregation] == :sum
|
|
39
|
+
scores[term] + weighted
|
|
40
|
+
else
|
|
41
|
+
[scores[term], weighted].max
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
module Mongoid
|
|
2
|
+
module FullTextSearch
|
|
3
|
+
# Plans search keys and obsolete indexes while retaining shared-model filters.
|
|
4
|
+
class IndexDefinition
|
|
5
|
+
attr_reader :keys, :obsolete_indexes
|
|
6
|
+
|
|
7
|
+
def initialize(filters, localized, existing_indexes)
|
|
8
|
+
filter_keys = (filters || {}).map { |key, _value| "filter_values.#{key}" }.sort
|
|
9
|
+
@keys = build_keys(filter_keys, localized)
|
|
10
|
+
correct_keys = @keys.map(&:first)
|
|
11
|
+
all_filter_keys = filter_keys.dup
|
|
12
|
+
@obsolete_indexes = existing_indexes.find_all do |index|
|
|
13
|
+
keys = index['key'].keys
|
|
14
|
+
next false unless keys.member?('ngram')
|
|
15
|
+
|
|
16
|
+
all_filter_keys |= keys.find_all { |key| key.start_with?('filter_values.') }
|
|
17
|
+
keys & correct_keys != correct_keys
|
|
18
|
+
end
|
|
19
|
+
@keys = build_keys(all_filter_keys.sort, localized) if all_filter_keys.length > filter_keys.length
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
private
|
|
23
|
+
|
|
24
|
+
def build_keys(filter_keys, localized)
|
|
25
|
+
keys = [['ngram', 1], ['score', -1]].concat(filter_keys.map { |key| [key, 1] })
|
|
26
|
+
keys.unshift(['locale', 1]) if localized
|
|
27
|
+
keys
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
require 'active_support'
|
|
2
|
+
require 'active_support/core_ext/enumerable'
|
|
3
|
+
require 'active_support/core_ext/string/multibyte'
|
|
4
|
+
require 'unicode_utils'
|
|
5
|
+
|
|
6
|
+
module Mongoid
|
|
7
|
+
module FullTextSearch
|
|
8
|
+
# Calculates query and document ngram scores without accessing persistence.
|
|
9
|
+
module Ngrams
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
def calculate(str, config, bound_number_returned = true)
|
|
13
|
+
return {} if str.nil?
|
|
14
|
+
|
|
15
|
+
filtered_str = normalize(str, config)
|
|
16
|
+
ngram_array = sliding_windows(filtered_str, config, bound_number_returned)
|
|
17
|
+
|
|
18
|
+
# Repeated windows contribute their maximum score, not their sum.
|
|
19
|
+
ngram_array = ngram_array.group_by { |h| h[:ngram] }.map do |key, values|
|
|
20
|
+
{ ngram: key, score: values.map { |v| v[:score] }.max }
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
if config[:index_short_prefixes] || config[:index_full_words]
|
|
24
|
+
split_regex_def = config[:word_separators].keys.map { |k| Regexp.escape(k) }.join
|
|
25
|
+
all_words = filtered_str.split(Regexp.compile("[#{split_regex_def}]"))
|
|
26
|
+
ngram_array.concat(short_prefixes(all_words, filtered_str, config)) if config[:index_short_prefixes]
|
|
27
|
+
ngram_array.concat(full_words(all_words, filtered_str, config)) if config[:index_full_words]
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Window, prefix, and full-word contributions add to the final score.
|
|
31
|
+
Hash[ngram_array.group_by { |h| h[:ngram] }.map { |key, values| [key, values.map { |v| v[:score] }.sum] }]
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def normalize(str, config)
|
|
35
|
+
if config[:remove_accents]
|
|
36
|
+
if defined?(UnicodeUtils)
|
|
37
|
+
str = UnicodeUtils.nfkd(str)
|
|
38
|
+
elsif defined?(DiacriticsFu)
|
|
39
|
+
str = DiacriticsFu.escape(str)
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
alphabet = config[:alphabet]
|
|
44
|
+
str.mb_chars.downcase.to_s.split('').find_all do |ch|
|
|
45
|
+
(alphabet.is_a?(Regexp) ? alphabet =~ ch : alphabet[ch]) || config[:word_separators][ch]
|
|
46
|
+
end.join('')
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def sliding_windows(str, config, bound_number_returned)
|
|
50
|
+
last_start = str.length - config[:ngram_width]
|
|
51
|
+
ngram_count = last_start + 1
|
|
52
|
+
ngram_count = [ngram_count, config[:max_ngrams_to_search]].min if bound_number_returned
|
|
53
|
+
|
|
54
|
+
# Sample both endpoints: three windows from 'abcdefghijk' are 'abc', 'efg', 'ijk'.
|
|
55
|
+
(0...ngram_count).map do |sample|
|
|
56
|
+
i = ngram_count == 1 ? 0 : (sample * last_start.to_f / (ngram_count - 1)).round
|
|
57
|
+
score = if i.zero? || (config[:apply_prefix_scoring_to_all_words] && \
|
|
58
|
+
config[:word_separators].key?(str[i - 1].chr))
|
|
59
|
+
Math.sqrt(1 + 1.0 / str.length)
|
|
60
|
+
else
|
|
61
|
+
Math.sqrt(2.0 / str.length)
|
|
62
|
+
end
|
|
63
|
+
{ ngram: str[i..i + config[:ngram_width] - 1], score: score }
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def short_prefixes(words, str, config)
|
|
68
|
+
prefixes_seen = {}
|
|
69
|
+
words.each_with_object([]) do |word, records|
|
|
70
|
+
next if word.length < config[:ngram_width] - 1
|
|
71
|
+
|
|
72
|
+
prefix = word[0...config[:ngram_width] - 1]
|
|
73
|
+
if prefixes_seen[prefix].nil? && (config[:stop_words][word].nil? || word == str)
|
|
74
|
+
records << { ngram: prefix, score: 1 + 1.0 / str.length }
|
|
75
|
+
prefixes_seen[prefix] = true
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def full_words(words, str, config)
|
|
81
|
+
full_words_seen = {}
|
|
82
|
+
words.each_with_object([]) do |word, records|
|
|
83
|
+
if word.length > 1 && full_words_seen[word].nil? && (config[:stop_words][word].nil? || word == str)
|
|
84
|
+
records << { ngram: word, score: 1 + 1.0 / str.length }
|
|
85
|
+
full_words_seen[word] = true
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
private_class_method :normalize, :sliding_windows, :short_prefixes, :full_words
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
end
|