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.
Files changed (57) hide show
  1. checksums.yaml +5 -5
  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 +131 -51
  10. data/.spellcheck.txt +181 -0
  11. data/CHANGELOG.md +57 -31
  12. data/Dangerfile +5 -1
  13. data/Gemfile +22 -18
  14. data/Gemfile.danger +5 -0
  15. data/README.md +171 -179
  16. data/RELEASING.md +60 -0
  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/indexable.rb +1 -1
  22. data/lib/mongoid/full_text_search/indexes.rb +1 -1
  23. data/lib/mongoid/full_text_search/ngrams.rb +93 -0
  24. data/lib/mongoid/full_text_search/version.rb +1 -1
  25. data/lib/mongoid/full_text_search.rb +112 -144
  26. data/mongoid_fulltext.gemspec +4 -4
  27. data/script/release.rb +13 -0
  28. data/spec/models/chinese_artwork.rb +7 -0
  29. data/spec/models/filtered_artist.rb +1 -2
  30. data/spec/models/filtered_artwork.rb +1 -2
  31. data/spec/models/filtered_other.rb +1 -2
  32. data/spec/models/localized_artwork.rb +29 -0
  33. data/spec/models/multilingual_artwork.rb +7 -0
  34. data/spec/models/partitioned_artist.rb +1 -1
  35. data/spec/models/russian_artwork.rb +1 -2
  36. data/spec/models/scoped_artwork.rb +14 -0
  37. data/spec/models/tagged_artwork.rb +9 -0
  38. data/spec/models/weighted_artwork.rb +34 -0
  39. data/spec/mongoid/array_fields_spec.rb +43 -0
  40. data/spec/mongoid/bulk_indexing_spec.rb +56 -0
  41. data/spec/mongoid/candidate_limits_spec.rb +19 -0
  42. data/spec/mongoid/criteria_search_spec.rb +73 -0
  43. data/spec/mongoid/full_text_search_spec.rb +41 -12
  44. data/spec/mongoid/localized_fields_spec.rb +197 -0
  45. data/spec/mongoid/ngram_sampling_spec.rb +55 -0
  46. data/spec/mongoid/non_latin_spec.rb +50 -0
  47. data/spec/mongoid/timeout_option_spec.rb +18 -0
  48. data/spec/mongoid/weighted_fields_spec.rb +102 -0
  49. data/spec/release/release_spec.rb +60 -0
  50. data/spec/spec_helper.rb +22 -7
  51. data/spec/support/mongoid.rb +6 -4
  52. data/spec/unit/field_scores_spec.rb +54 -0
  53. data/spec/unit/index_definition_spec.rb +48 -0
  54. data/spec/unit/ngrams_spec.rb +73 -0
  55. data/spec/version_spec.rb +7 -0
  56. metadata +62 -11
  57. data/.travis.yml +0 -30
@@ -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
@@ -0,0 +1,73 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Scoped full-text searches' do
4
+ it 'combines criteria with locale filtering' do
5
+ I18n.with_locale(:en) do
6
+ included = LocalizedArtwork.create!(title_translations: { 'en' => 'Flowers' }, artist: 'Picasso')
7
+ LocalizedArtwork.create!(title_translations: { 'en' => 'Flowers' }, artist: 'Monet')
8
+ expect(LocalizedArtwork.where(artist: 'Picasso').fulltext_search('flowers')).to eq([included])
9
+ end
10
+ end
11
+
12
+ it 'applies criteria without raising for excluded documents' do
13
+ excluded = ScopedArtwork.create!(title: 'My Doc', value: 0)
14
+ included = ScopedArtwork.create!(title: 'My Doc 2', value: 10)
15
+ expect(ScopedArtwork.where(value: 10).fulltext_search('doc')).to eq([included])
16
+ expect(ScopedArtwork.fulltext_search('doc')).to include(excluded, included)
17
+ end
18
+
19
+ it 'fills the result limit after filtering higher-ranked documents' do
20
+ ScopedArtwork.create!(title: 'Flowers', value: 0)
21
+ included = ScopedArtwork.create!(title: 'Flowers in a vase', value: 10)
22
+ expect(ScopedArtwork.where(value: 10).fulltext_search('flowers', max_results: 1)).to eq([included])
23
+ end
24
+
25
+ it 'combines criteria on document ids with the result limit' do
26
+ ScopedArtwork.create!(title: 'Flowers')
27
+ included = ScopedArtwork.create!(title: 'Flowers in a vase')
28
+ expect(ScopedArtwork.where(id: included.id).fulltext_search('flowers', max_results: 1)).to eq([included])
29
+ end
30
+
31
+ it 'preserves scores and relevance order in a scoped search' do
32
+ first = ScopedArtwork.create!(title: 'Flowers', value: 10)
33
+ second = ScopedArtwork.create!(title: 'Flowers in a vase', value: 10)
34
+ results = ScopedArtwork.where(value: 10).fulltext_search('flowers', return_scores: true)
35
+ expect(results.map(&:first)).to eq([first, second])
36
+ expect(results.first.last).to be > results.last.last
37
+ end
38
+
39
+ it 'preserves the existing zero-limit behavior for unscoped searches' do
40
+ first = ScopedArtwork.create!(title: 'Flowers')
41
+ second = ScopedArtwork.create!(title: 'Flowers in a vase')
42
+ expect(ScopedArtwork.fulltext_search('flowers', max_results: 0)).to eq([first, second])
43
+ end
44
+
45
+ it 'searches descendants without returning parent or sibling documents' do
46
+ parent = ScopedArtwork.create!(title: 'My Doc')
47
+ child = InheritedArtwork.create!(title: 'My Inherited Doc')
48
+ grandchild = FurtherInheritedArtwork.create!(title: 'My Further Inherited Doc')
49
+ expect(ScopedArtwork.fulltext_search('doc')).to match_array([parent, child, grandchild])
50
+ expect(InheritedArtwork.fulltext_search('doc')).to match_array([child, grandchild])
51
+ expect(FurtherInheritedArtwork.fulltext_search('doc')).to eq([grandchild])
52
+ end
53
+
54
+ it 'does not raise for dangling index references even when Mongoid raises on find' do
55
+ artwork = ScopedArtwork.create!(title: 'Flowers')
56
+ artwork.delete
57
+ previous = Mongoid.raise_not_found_error
58
+ begin
59
+ Mongoid.raise_not_found_error = true
60
+ expect(ScopedArtwork.fulltext_search('flowers')).to eq([])
61
+ expect(ScopedArtwork.fulltext_search('flowers', return_scores: true)).to eq([])
62
+ ensure
63
+ Mongoid.raise_not_found_error = previous
64
+ end
65
+ end
66
+
67
+ it 'keeps unscoped shared-index searches across unrelated models' do
68
+ artist = ExternalArtist.create!(full_name: 'Picasso')
69
+ artwork = ExternalArtwork.create!(title: 'Picasso')
70
+ expect(ExternalArtwork.fulltext_search('picasso')).to match_array([artist, artwork])
71
+ expect(ExternalArtwork.where(title: 'Picasso').fulltext_search('picasso')).to eq([artwork])
72
+ end
73
+ end
@@ -1,4 +1,3 @@
1
- # coding: utf-8
2
1
  require 'spec_helper'
3
2
 
4
3
  describe Mongoid::FullTextSearch do
@@ -355,6 +354,8 @@ describe Mongoid::FullTextSearch do
355
354
  # fields as well as the union of all the filter fields to allow for efficient lookups.
356
355
 
357
356
  it 'creates a proper index for searching efficiently' do
357
+ # see https://github.com/mongoid/mongoid_fulltext/pull/39
358
+ pending unless Mongoid::Compatibility::Version.mongoid5_or_newer?
358
359
  [FilteredArtwork, FilteredArtist, FilteredOther].each(&:create_indexes)
359
360
  index_collection = FilteredArtwork.collection.database['mongoid_fulltext.artworks_and_artists']
360
361
  ngram_indexes = []
@@ -421,7 +422,7 @@ describe Mongoid::FullTextSearch do
421
422
  let!(:somao) { ExternalArtwork.create(title: 'Somao by Randy Morehall') }
422
423
 
423
424
  it "returns basic matches that don't match a whole word and aren't prefixes with score < 1" do
424
- %w(paox porehall).each do |query|
425
+ %w[paox porehall].each do |query|
425
426
  results = ExternalArtist.fulltext_search(query, return_scores: true)
426
427
  expect(results.length).to be > 0
427
428
  expect(results.map { |result| result[-1] }.inject(true) { |accum, item| accum &= (item < 1) }).to be_truthy
@@ -429,15 +430,15 @@ describe Mongoid::FullTextSearch do
429
430
  end
430
431
 
431
432
  it 'returns prefix matches with a score >= 1 but < 2' do
432
- %w(warho rand).each do |query|
433
+ %w[warho rand].each do |query|
433
434
  results = ExternalArtist.fulltext_search(query, return_scores: true)
434
435
  expect(results.length).to be > 0
435
- expect(results.map { |result| result[-1] if result[0].to_s.starts_with?(query) }.compact.inject(true) { |accum, item| accum &= (item >= 1 && item < 2) }).to be_truthy
436
+ expect(results.map { |result| result[-1] if result[0].to_s.starts_with?(query) }.compact.inject(true) { |accum, item| accum &= item >= 1 && item < 2 }).to be_truthy
436
437
  end
437
438
  end
438
439
 
439
440
  it 'returns full-word matches with a score >= 2' do
440
- %w(andy warhol mao).each do |query|
441
+ %w[andy warhol mao].each do |query|
441
442
  results = ExternalArtist.fulltext_search(query, return_scores: true)
442
443
  expect(results.length).to be > 0
443
444
  expect(results.map { |result| result[-1] if result[0].to_s.split(' ').member?(query) }.compact.inject(true) { |accum, item| accum &= (item >= 2) }).to be_truthy
@@ -489,8 +490,8 @@ describe Mongoid::FullTextSearch do
489
490
  end
490
491
 
491
492
  context 'remove_from_ngram_index' do
492
- let!(:flowers1) { BasicArtwork.create(title: 'Flowers 1') }
493
- let!(:flowers2) { BasicArtwork.create(title: 'Flowers 1') }
493
+ let!(:flowers1) { BasicArtwork.create(title: 'Flowers 1') }
494
+ let!(:flowers2) { BasicArtwork.create(title: 'Flowers 1') }
494
495
 
495
496
  it 'removes all records from the index' do
496
497
  BasicArtwork.remove_from_ngram_index
@@ -504,8 +505,8 @@ describe Mongoid::FullTextSearch do
504
505
  end
505
506
 
506
507
  context 'update_ngram_index' do
507
- let!(:flowers1) { BasicArtwork.create(title: 'Flowers 1') }
508
- let!(:flowers2) { BasicArtwork.create(title: 'Flowers 2') }
508
+ let!(:flowers1) { BasicArtwork.create(title: 'Flowers 1') }
509
+ let!(:flowers2) { BasicArtwork.create(title: 'Flowers 2') }
509
510
 
510
511
  context 'when config[:update_if] exists' do
511
512
  let(:painting) { BasicArtwork.new title: 'Painting' }
@@ -568,7 +569,7 @@ describe Mongoid::FullTextSearch do
568
569
 
569
570
  context 'and is not a symbol, string, or proc' do
570
571
  before(:each) do
571
- conditional_index[:update_if] = %w(this isn't a symbol, string, or proc)
572
+ conditional_index[:update_if] = %w[this isn't a symbol string or proc]
572
573
  end
573
574
 
574
575
  it "doesn't update the index for the document" do
@@ -597,7 +598,7 @@ describe Mongoid::FullTextSearch do
597
598
  context 'incremental' do
598
599
  it 'removes an existing record' do
599
600
  coll = Mongoid.default_session['mongoid_fulltext.index_basicartwork_0']
600
- if Mongoid::Compatibility::Version.mongoid5? || Mongoid::Compatibility::Version.mongoid6?
601
+ if Mongoid::Compatibility::Version.mongoid5_or_newer?
601
602
  coll.find('document_id' => flowers1._id).delete_many
602
603
  else
603
604
  coll.find('document_id' => flowers1._id).remove_all
@@ -609,11 +610,13 @@ describe Mongoid::FullTextSearch do
609
610
 
610
611
  context 'mongoid indexes' do
611
612
  it 'can re-create dropped indexes' do
613
+ # see https://github.com/mongoid/mongoid_fulltext/pull/39
614
+ pending unless Mongoid::Compatibility::Version.mongoid5_or_newer?
612
615
  # there're no indexes by default as Mongoid.autocreate_indexes is set to false
613
616
  # but mongo will automatically attempt to index _id in the background
614
617
  expect(Mongoid.default_session['mongoid_fulltext.index_basicartwork_0'].indexes.count).to be <= 1
615
618
  BasicArtwork.create_indexes
616
- expected_indexes = %w(_id_ fts_index document_id_1).sort
619
+ expected_indexes = %w[_id_ fts_index document_id_1].sort
617
620
  current_indexes = []
618
621
  Mongoid.default_session['mongoid_fulltext.index_basicartwork_0'].indexes.each do |idef|
619
622
  current_indexes << idef['name']
@@ -630,6 +633,18 @@ describe Mongoid::FullTextSearch do
630
633
  BasicArtwork.create_indexes
631
634
  end
632
635
  end
636
+
637
+ context 'using update index options' do
638
+ it 'will not timeout' do
639
+ expect(BasicArtwork).to receive_message_chain(:all, :no_timeout).and_return([])
640
+ BasicArtwork.update_ngram_index(timeout: false)
641
+ end
642
+
643
+ it 'will timeout' do
644
+ expect(BasicArtwork).to receive_message_chain(:all).and_return([])
645
+ BasicArtwork.update_ngram_index(timeout: true)
646
+ end
647
+ end
633
648
  end
634
649
 
635
650
  context 'batched reindexing' do
@@ -642,6 +657,20 @@ describe Mongoid::FullTextSearch do
642
657
  end
643
658
  end
644
659
 
660
+ context 'creating indexes before any documents exist' do
661
+ it 'creates both indexes in a missing collection without inserting documents' do
662
+ coll = BasicArtwork.collection.database[BasicArtwork.mongoid_fulltext_config.keys.first]
663
+ BasicArtwork.create_indexes
664
+ coll.drop
665
+ BasicArtwork.create_indexes
666
+
667
+ indexes = []
668
+ coll.indexes.each { |index| indexes << index['name'] }
669
+ expect(indexes).to include('fts_index', 'document_id_1') if Mongoid::Compatibility::Version.mongoid5_or_newer?
670
+ expect(coll.find.count).to eq(0)
671
+ end
672
+ end
673
+
645
674
  # For =~ operator documentation
646
675
  # https://github.com/dchelimsky/rspec/blob/master/lib/spec/matchers/match_array.rb#L53
647
676
 
@@ -0,0 +1,197 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Localized fields' do
4
+ around do |example|
5
+ locales = I18n.available_locales
6
+ begin
7
+ I18n.available_locales = %i[en cs]
8
+ I18n.with_locale(:en) { example.run }
9
+ ensure
10
+ I18n.available_locales = locales
11
+ end
12
+ end
13
+
14
+ let(:artwork) { LocalizedArtwork.create!(title_translations: { 'en' => 'Flowers', 'cs' => 'Kvetiny' }, artist: 'Picasso') }
15
+
16
+ it 'searches the current locale only' do
17
+ artwork
18
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([artwork])
19
+ expect(LocalizedArtwork.fulltext_search('kvetiny')).to eq([])
20
+ I18n.with_locale(:cs) do
21
+ expect(LocalizedArtwork.fulltext_search('kvetiny')).to eq([artwork])
22
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([])
23
+ end
24
+ end
25
+
26
+ it 'indexes scalar fields and computed methods in every locale' do
27
+ artwork
28
+ %i[en cs].each do |locale|
29
+ I18n.with_locale(locale) { expect(LocalizedArtwork.fulltext_search('picasso')).to eq([artwork]) }
30
+ end
31
+ expect(LocalizedArtwork.fulltext_search('english')).to eq([artwork])
32
+ I18n.with_locale(:cs) { expect(LocalizedArtwork.fulltext_search('cesky')).to eq([artwork]) }
33
+ end
34
+
35
+ it 'evaluates filters in the locale of the index' do
36
+ artwork
37
+ expect(LocalizedArtwork.fulltext_search('flowers', language: 'en')).to eq([artwork])
38
+ I18n.with_locale(:cs) { expect(LocalizedArtwork.fulltext_search('kvetiny', language: 'cs')).to eq([artwork]) }
39
+ end
40
+
41
+ it 'replaces all translations without changing the caller locale' do
42
+ artwork
43
+ I18n.with_locale(:cs) do
44
+ artwork.title_translations = { 'en' => 'Painting', 'cs' => 'Obraz' }
45
+ artwork.save!
46
+ expect(I18n.locale).to eq(:cs)
47
+ expect(LocalizedArtwork.fulltext_search('kvetiny')).to eq([])
48
+ expect(LocalizedArtwork.fulltext_search('obraz')).to eq([artwork])
49
+ end
50
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([])
51
+ expect(LocalizedArtwork.fulltext_search('painting')).to eq([artwork])
52
+ end
53
+
54
+ it 'continues after an empty translation in the first locale' do
55
+ document = OnlyLocalizedArtwork.create!(title_translations: { 'en' => '', 'cs' => 'Obraz' })
56
+ I18n.with_locale(:cs) { expect(OnlyLocalizedArtwork.fulltext_search('obraz')).to eq([document]) }
57
+ end
58
+
59
+ it 'removes records for a translation that becomes empty' do
60
+ document = OnlyLocalizedArtwork.create!(title_translations: { 'en' => 'Flowers', 'cs' => 'Obraz' })
61
+ document.title_translations = { 'en' => 'Flowers', 'cs' => '' }
62
+ document.save!
63
+ expect(OnlyLocalizedArtwork.fulltext_search('flowers')).to eq([document])
64
+ I18n.with_locale(:cs) { expect(OnlyLocalizedArtwork.fulltext_search('obraz')).to eq([]) }
65
+ end
66
+
67
+ it 'evaluates update_if independently in each locale' do
68
+ config = OnlyLocalizedArtwork.mongoid_fulltext_config.values.first
69
+ begin
70
+ config[:update_if] = ->(_document) { I18n.locale == :cs }
71
+ document = OnlyLocalizedArtwork.create!(title_translations: { 'en' => 'Flowers', 'cs' => 'Obraz' })
72
+ expect(OnlyLocalizedArtwork.fulltext_search('flowers')).to eq([])
73
+ I18n.with_locale(:cs) { expect(OnlyLocalizedArtwork.fulltext_search('obraz')).to eq([document]) }
74
+ ensure
75
+ config.delete(:update_if)
76
+ end
77
+ end
78
+
79
+ it 'removes all locale indexes for a document' do
80
+ artwork.destroy
81
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([])
82
+ I18n.with_locale(:cs) { expect(LocalizedArtwork.fulltext_search('kvetiny')).to eq([]) }
83
+ end
84
+
85
+ it 'removes and rebuilds all locales through the class API' do
86
+ artwork
87
+ LocalizedArtwork.remove_from_ngram_index
88
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([])
89
+ I18n.with_locale(:cs) { expect(LocalizedArtwork.fulltext_search('kvetiny')).to eq([]) }
90
+ LocalizedArtwork.update_ngram_index
91
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([artwork])
92
+ I18n.with_locale(:cs) { expect(LocalizedArtwork.fulltext_search('kvetiny')).to eq([artwork]) }
93
+ end
94
+
95
+ it 'stores locales together in the original index collection' do
96
+ artwork
97
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
98
+ records = LocalizedArtwork.collection.database[name].find.to_a
99
+ expect(records.map { |record| record['locale'] }.uniq.sort).to eq(%w[cs en])
100
+ expect(records.map { |record| record['document_id'] }.uniq).to eq([artwork.id])
101
+ names = []
102
+ LocalizedArtwork.each_fulltext_index { |index_name, _config| names << index_name }
103
+ expect(names).to eq([name, name])
104
+ end
105
+
106
+ it 'keeps the same collection when available locales change' do
107
+ I18n.available_locales = [:en]
108
+ artwork
109
+ I18n.available_locales = %i[en cs]
110
+ expect(LocalizedArtwork.fulltext_search('flowers')).to eq([artwork])
111
+ end
112
+
113
+ it 'leaves nonlocalized index records unchanged' do
114
+ artwork = PartlyLocalizedArtwork.create!(artist: 'Picasso')
115
+ expect(PartlyLocalizedArtwork.fulltext_search('picasso')).to eq([artwork])
116
+ collections = []
117
+ PartlyLocalizedArtwork.each_fulltext_index { |name, _config| collections << name }
118
+ expect(collections).to eq(['mongoid_fulltext.untranslated'])
119
+ records = PartlyLocalizedArtwork.collection.database[collections.first].find.to_a
120
+ expect(records).not_to be_empty
121
+ expect(records.any? { |record| record.key?('locale') }).to eq(false)
122
+ end
123
+
124
+ it 'restores the caller locale when a field reader raises' do
125
+ document = LocalizedArtwork.new
126
+ allow(document).to receive(:description).and_raise('reader failure')
127
+ I18n.with_locale(:cs) do
128
+ expect { document.update_ngram_index }.to raise_error(RuntimeError, 'reader failure')
129
+ expect(I18n.locale).to eq(:cs)
130
+ end
131
+ end
132
+
133
+ it 'creates a locale-prefixed compound index in the original collection' do
134
+ LocalizedArtwork.create_indexes
135
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
136
+ indexes = []
137
+ LocalizedArtwork.collection.database[name].indexes.each { |index| indexes << index }
138
+ if Mongoid::Compatibility::Version.mongoid5_or_newer?
139
+ expect(indexes.map { |index| index['name'] }).to include('fts_index', 'document_id_1')
140
+ keys = indexes.find { |index| index['name'] == 'fts_index' }['key']
141
+ expect(keys.to_a).to eq([['locale', 1], ['ngram', 1], ['score', -1], ['filter_values.language', 1]])
142
+ end
143
+ expect(I18n.locale).to eq(:en)
144
+ end
145
+
146
+ it 'removes records for every locale even after a locale is no longer configured' do
147
+ artwork
148
+ I18n.available_locales = [:en]
149
+ artwork.remove_from_ngram_index
150
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
151
+ expect(LocalizedArtwork.collection.database[name].find.count).to eq(0)
152
+ end
153
+
154
+ it 'removes unconfigured locales through the class API' do
155
+ artwork
156
+ I18n.available_locales = [:en]
157
+ LocalizedArtwork.remove_from_ngram_index
158
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
159
+ expect(LocalizedArtwork.collection.database[name].find.count).to eq(0)
160
+ end
161
+
162
+ it 'destroys records for locales that are no longer configured' do
163
+ artwork
164
+ I18n.available_locales = [:en]
165
+ artwork.destroy
166
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
167
+ expect(LocalizedArtwork.collection.database[name].find.count).to eq(0)
168
+ end
169
+
170
+ it 'upgrades an existing search index to include locale' do
171
+ next unless Mongoid::Compatibility::Version.mongoid5_or_newer?
172
+
173
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
174
+ coll = LocalizedArtwork.collection.database[name]
175
+ coll.indexes.drop_all
176
+ coll.indexes.create_one({ 'ngram' => 1, 'score' => -1 }, name: 'fts_index')
177
+ LocalizedArtwork.create_indexes
178
+ keys = coll.indexes.find { |index| index['name'] == 'fts_index' }['key']
179
+ expect(keys.keys.first).to eq('locale')
180
+ end
181
+
182
+ it 'keeps scores isolated when the same term exists in both locales' do
183
+ artwork
184
+ en_score = LocalizedArtwork.fulltext_search('picasso', return_scores: true).first.last
185
+ cs_score = I18n.with_locale(:cs) { LocalizedArtwork.fulltext_search('picasso', return_scores: true).first.last }
186
+ config = LocalizedArtwork.mongoid_fulltext_config.values.first
187
+ name = LocalizedArtwork.mongoid_fulltext_config.keys.first
188
+ coll = LocalizedArtwork.collection.database[name]
189
+ %w[en cs].zip([en_score, cs_score]).each do |locale, score|
190
+ query_ngrams = LocalizedArtwork.all_ngrams('picasso', config)
191
+ expected = coll.find('locale' => locale).inject(0.0) do |sum, record|
192
+ sum + record['score'] * (query_ngrams[record['ngram']] || 0)
193
+ end
194
+ expect(score).to be_within(0.00001).of(expected)
195
+ end
196
+ end
197
+ end
@@ -0,0 +1,55 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Bounded ngram sampling' do
4
+ let(:config) do
5
+ BasicArtwork.mongoid_fulltext_config.values.first.merge(
6
+ max_ngrams_to_search: 3, index_full_words: false, index_short_prefixes: false
7
+ )
8
+ end
9
+
10
+ it 'preserves the model calculation entry point and its unbounded option' do
11
+ expect(Mongoid::FullTextSearch::Ngrams).to receive(:calculate).with('abcdef', config, false).and_call_original
12
+ expect(BasicArtwork.all_ngrams('abcdef', config, false).keys).to eq(%w[abc bcd cde def])
13
+ end
14
+
15
+ it 'selects the documented evenly spaced sample including the last ngram' do
16
+ expect(BasicArtwork.all_ngrams('abcdefghijk', config).keys).to eq(%w[abc efg ijk])
17
+ expect(BasicArtwork.all_ngrams('abcdefghij', config).keys).to eq(%w[abc efg hij])
18
+ end
19
+
20
+ it 'never exceeds the configured number of sliding-window ngrams' do
21
+ (1..12).each do |limit|
22
+ (0..26).each do |length|
23
+ text = 'abcdefghijklmnopqrstuvwxyz'[0, length]
24
+ ngrams = BasicArtwork.all_ngrams(text, config.merge(max_ngrams_to_search: limit))
25
+ expected_count = [[length - config[:ngram_width] + 1, 0].max, limit].min
26
+ expect(ngrams.length).to eq(expected_count)
27
+ next unless expected_count > 1
28
+
29
+ expect(ngrams.keys.first).to eq(text[0, 3])
30
+ expect(ngrams.keys.last).to eq(text[-3, 3])
31
+ end
32
+ end
33
+ end
34
+
35
+ it 'selects the prefix when only one ngram is requested' do
36
+ expect(BasicArtwork.all_ngrams('abcdefghijk', config.merge(max_ngrams_to_search: 1)).keys).to eq(['abc'])
37
+ end
38
+
39
+ it 'still indexes every sliding window when the bound is disabled' do
40
+ expect(BasicArtwork.all_ngrams('abcdefghijk', config, false).keys).to eq(%w[abc bcd cde def efg fgh ghi hij ijk])
41
+ end
42
+
43
+ it 'preserves full-word and short-prefix bonuses in addition to sampled ngrams' do
44
+ options = config.merge(index_full_words: true, index_short_prefixes: true)
45
+ expect(BasicArtwork.all_ngrams('abcdefghijk', options).keys).to eq(%w[abc efg ijk ab abcdefghijk])
46
+ end
47
+
48
+ it 'rejects a nonpositive or noninteger search bound' do
49
+ [0, -1, 1.5, nil].each do |limit|
50
+ expect do
51
+ BasicArtwork.fulltext_search_in :title, max_ngrams_to_search: limit
52
+ end.to raise_error(ArgumentError, ':max_ngrams_to_search must be a positive integer')
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,50 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Non-Latin alphabets' do
4
+ it 'searches Chinese characters included in the configured alphabet' do
5
+ artwork = ChineseArtwork.create!(title: "\u5367\u864e\u85cf\u9f99")
6
+ expect(ChineseArtwork.fulltext_search("\u85cf\u9f99")).to eq([artwork])
7
+ expect(ChineseArtwork.fulltext_search("\u5367\u864e")).to eq([artwork])
8
+ end
9
+
10
+ it 'does not index characters outside the configured alphabet' do
11
+ artwork = BasicArtwork.create!(title: "\u5367\u864e\u85cf\u9f99")
12
+ expect(BasicArtwork.fulltext_search(artwork.title)).to eq([])
13
+ end
14
+
15
+ it 'supports Han characters outside the example title without enumerating them' do
16
+ artwork = ChineseArtwork.create!(title: "\u4e2d\u6587\u641c\u7d22")
17
+ expect(ChineseArtwork.fulltext_search("\u641c\u7d22")).to eq([artwork])
18
+ expect(ChineseArtwork.fulltext_search("\u4e2d\u6587")).to eq([artwork])
19
+ expect(ChineseArtwork.fulltext_search('search')).to eq([])
20
+ end
21
+
22
+ it 'supports Unicode letters, combining marks, and numbers across scripts' do
23
+ artwork = MultilingualArtwork.create!(title: "Flowers \u0428\u0418\u0428\u041a\u0418\u041d \u4e2d\u6587 123")
24
+ %w[flowers шишкин 中文 123].each do |query|
25
+ expect(MultilingualArtwork.fulltext_search(query)).to eq([artwork])
26
+ end
27
+ config = MultilingualArtwork.mongoid_fulltext_config.values.first.merge(index_full_words: false)
28
+ expect(MultilingualArtwork.all_ngrams("e\u0301", config).keys).to eq(["e\u0301"])
29
+ end
30
+
31
+ it 'retains word separators independently of the regular expression' do
32
+ config = ChineseArtwork.mongoid_fulltext_config.values.first.merge(index_full_words: false)
33
+ expect(ChineseArtwork.all_ngrams("\u4e2d-\u6587", config).keys).to eq(["\u4e2d-", "-\u6587"])
34
+ expect(ChineseArtwork.all_ngrams("\u4e2d!\u6587", config).keys).to eq(["\u4e2d\u6587"])
35
+ end
36
+
37
+ it 'preserves explicit string allowlists' do
38
+ expect(RussianArtwork.mongoid_fulltext_config.values.first[:alphabet]).to be_a(Hash)
39
+ artwork = RussianArtwork.create!(title: "\u0428\u0438\u0448\u043a\u0438\u043d")
40
+ expect(RussianArtwork.fulltext_search("\u0448\u0438\u0448\u043a\u0438\u043d")).to eq([artwork])
41
+ end
42
+
43
+ it 'rejects unsupported alphabet types at declaration time' do
44
+ [nil, [], 123].each do |alphabet|
45
+ expect do
46
+ ChineseArtwork.fulltext_search_in :title, alphabet: alphabet
47
+ end.to raise_error(ArgumentError, ':alphabet must be a String or Regexp')
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,18 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'Class-level indexing timeout options' do
4
+ it 'rebuilds all records with cursor timeouts disabled' do
5
+ first = DelayedArtwork.create!(title: 'Flowers 1')
6
+ second = DelayedArtwork.create!(title: 'Flowers 2')
7
+ expect(DelayedArtwork.fulltext_search('flower')).to eq([])
8
+ DelayedArtwork.update_ngram_index(timeout: false)
9
+ expect(DelayedArtwork.fulltext_search('flower')).to match_array([first, second])
10
+ end
11
+
12
+ it 'applies the no_timeout option to the class criteria' do
13
+ items = DelayedArtwork.all
14
+ expect(DelayedArtwork).to receive(:all).and_return(items)
15
+ expect(items).to receive(:no_timeout).and_call_original
16
+ DelayedArtwork.update_ngram_index(timeout: false)
17
+ end
18
+ end