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
data/RELEASING.md CHANGED
@@ -1,43 +1,60 @@
1
1
  # Releasing `mongoid_fulltext`
2
- ## Guidelines
3
- Generally, `mongoid_fulltext` should be released with enthusiasm but care. Release bug fixes as added, features as desired, and breaking API changes as absolutely necessary.
4
2
 
5
- ## This is how we do it.
6
- 1. Run the test suite in your local environment first, and ensure that everything's passing.
3
+ Releases use [ruby-gem-release](https://github.com/dblock/ruby-gem-release) 0.9.0 through a manually dispatched [Release workflow](.github/workflows/release.yml). Keep the `ruby-gem-release` gem in [Gemfile](Gemfile) and the reusable workflow in `release.yml` pinned to the same version. The workflow publishes through RubyGems Trusted Publishing, so no RubyGems API key or one-time password is needed. It only runs from `master` in `mongoid/mongoid_fulltext`.
7
4
 
8
- ```bash
9
- bundle install
10
- rake
11
- ```
5
+ The local Bundler `rake release`, `release:rubygem_push`, and `release:source_control_push` tasks are disabled so that releases only happen through the workflow.
12
6
 
13
- 2. Run the test suite on [Travis](https://travis-ci.org) to be certain that your changes work in a variety of environments. Only merge and release when all tests are passing.
7
+ ## One-Time Setup
14
8
 
15
- 3. Bump the version in [`lib/mongoid/full_text_search/version.rb`](lib/mongoid/full_text_search/version.rb).
9
+ Before the first automated release, a maintainer must:
16
10
 
17
- * If the release fixes bugs or adds features with negligible impact, increment the third number (e.g., `0.3.2` → `0.3.3`).
18
- * If the release adds significant new features, increment the second number and zero out the third (e.g., `0.3.2` → `0.4.0`).
19
- * If the release adds breaking API changes, increment the first number and zero out the second and third (e.g., `0.3.2` → `1.0.0`).
11
+ 1. Create the GitHub environment `release` in `mongoid/mongoid_fulltext`, for example with `gh api --method PUT repos/mongoid/mongoid_fulltext/environments/release`, and restrict its deployment branches to `master`. Add required reviewers to the environment to require maintainer approval before publication.
12
+ 2. At [mongoid_fulltext's trusted publishers](https://rubygems.org/gems/mongoid_fulltext/trusted_publishers), add a GitHub Actions publisher with repository owner `mongoid`, repository `mongoid_fulltext`, workflow filename `release.yml`, environment `release`, and the separate workflow repository owner `dblock` and repository `ruby-gem-release`.
13
+ 3. Allow GitHub Actions to push release commits and `v*` tags to `master`. The workflow uses `GITHUB_TOKEN` with `contents: write` and `id-token: write`, and pushes the release commit and the next development version directly to `master`. See the upstream [setup and permissions guidance](https://github.com/dblock/ruby-gem-release/blob/v0.9.0/RELEASING.md#one-time-setup).
20
14
 
21
- You've gotta know it---it's semantic!
15
+ Installing the workflow does not apply these settings. To verify them without publishing, run a [dry run](https://github.com/dblock/ruby-gem-release/blob/v0.9.0/docs/actions/release.md#dry-run). It checks release prerequisites, including Trusted Publishing, without editing files, building, pushing, or publishing:
22
16
 
23
- 4. Add a header for the new version to [`CHANGELOG.md`](CHANGELOG.md) and list all the changes your release will include underneath it, crediting contributors as appropriate.
17
+ ```sh
18
+ gh workflow run release.yml --repo mongoid/mongoid_fulltext --ref master -f dry-run=true
19
+ ```
24
20
 
25
- 6. Update the [`README`](README.md) to document any new features. Remove any warnings indicating that users are reading the documentation for an unreleased version.
21
+ ## Prepare
26
22
 
27
- 7. Commit your changes...
23
+ Start with a clean, up-to-date `master`, and verify that the latest [CI checks](https://github.com/mongoid/mongoid_fulltext/actions) pass for all supported Ruby, Mongoid, and MongoDB versions. Review [CHANGELOG.md](CHANGELOG.md), [UPGRADING.md](UPGRADING.md), and [README.md](README.md) for new features.
28
24
 
29
- ```bash
30
- git add README.md CHANGELOG.md lib/mongoid/full_text_search/version.rb
31
- git commit -m "Preparing for release, 0.4.0."
32
- git push origin master
33
- ```
25
+ Follow semantic versioning: patch for fixes, minor for backward-compatible features, major for breaking changes. Check `Mongoid::FullTextSearch::VERSION` in [lib/mongoid/full_text_search/version.rb](lib/mongoid/full_text_search/version.rb), and the matching `### x.y.z (Next)` heading in [CHANGELOG.md](CHANGELOG.md). Change both in a pull request, or pass a `version` override when dispatching.
34
26
 
35
- 8. ...and do the thing!
27
+ Keep the `(Next)` heading. The workflow dates it using `YYYY/MM/DD` and removes the `* Your contribution here.` placeholder if present. A section with no notes cannot be released.
36
28
 
37
- ```bash
38
- rake release
39
- #=> mongoid_fulltext 0.4.0 built to pkg/mongoid_fulltext-0.4.0.gem
40
- #=> Tagged 0.4.0.
41
- #=> Pushed git commits and tags.
42
- #=> Pushed mongoid_fulltext 0.4.0 to rubygems.org.
43
- ```
29
+ Release automation requires MRI Ruby 3.3 or newer; the release dependency and tasks are skipped on older Ruby versions and JRuby. Release specs in [spec/release](spec/release) run the actual release tasks against a local fixture, using the [ruby-gem-release RSpec helpers](https://github.com/dblock/ruby-gem-release/blob/v0.9.0/docs/testing.md), without contacting RubyGems or GitHub.
30
+
31
+ ```sh
32
+ bundle install
33
+ bundle exec rake
34
+ ```
35
+
36
+ ## Publish
37
+
38
+ Dispatch the checked-in version:
39
+
40
+ ```sh
41
+ gh workflow run release.yml --repo mongoid/mongoid_fulltext --ref master
42
+ ```
43
+
44
+ To release a different version, pass an override:
45
+
46
+ ```sh
47
+ gh workflow run release.yml --repo mongoid/mongoid_fulltext --ref master -f version=1.0.0
48
+ ```
49
+
50
+ Dispatching starts a real release, not a dry run. Do not merge into `master` while a release runs.
51
+
52
+ The workflow prepares the release commit, starts MongoDB 8.0, runs RuboCop and specs with Mongoid 9 on Ruby 3.3, builds the gem, preserves recovery artifacts, publishes to RubyGems, pushes the release commit and `v` tag, and creates a GitHub Release with the changelog notes and the gem attached. It then increments the patch version, adds a new `(Next)` section with the placeholder, and pushes the next development commit to `master`. For a planned minor or major next version, change it in a later pull request.
53
+
54
+ Verify the published version on [RubyGems](https://rubygems.org/gems/mongoid_fulltext), the tag, the [GitHub Release](https://github.com/mongoid/mongoid_fulltext/releases), and the next development commit. The workflow does not replace the full CI matrix.
55
+
56
+ ## Recover a Partial Release
57
+
58
+ Inspect the failed run, RubyGems, remote commits and tags, and the GitHub Release before retrying. Publication may have succeeded even if a later Git push or next development commit failed. Never move a published tag or republish a version with different contents.
59
+
60
+ Use the run's retained recovery artifacts and the upstream [recovery instructions](https://github.com/dblock/ruby-gem-release/blob/v0.9.0/docs/actions/release.md#recovery-artifacts) to finish the release with the exact prepared commit and gem.
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
- require 'rubocop/rake_task'
14
- RuboCop::RakeTask.new(:rubocop)
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: %i[rubocop spec]
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
@@ -1,5 +1,5 @@
1
1
  module Mongoid
2
2
  module FullTextSearch
3
- VERSION = '0.8.2'.freeze
3
+ VERSION = '0.9.0'.freeze
4
4
  end
5
5
  end