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/README.md CHANGED
@@ -1,32 +1,26 @@
1
- Mongoid Fulltext Search
2
- =======================
1
+ # Mongoid Fulltext Search
3
2
 
4
- [![Gem Version](https://badge.fury.io/rb/mongoid_fulltext.svg)](http://badge.fury.io/rb/mongoid_fulltext)
5
- [![Build Status](https://secure.travis-ci.org/mongoid/mongoid_fulltext.svg)](http://travis-ci.org/mongoid/mongoid_fulltext)
6
- [![Code Climate](https://codeclimate.com/github/mongoid/mongoid_fulltext/badges/gpa.svg)](https://codeclimate.com/github/mongoid/mongoid_fulltext)
3
+ [![Gem Version](https://badge.fury.io/rb/mongoid_fulltext.svg)](https://badge.fury.io/rb/mongoid_fulltext) [![Test](https://github.com/mongoid/mongoid_fulltext/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/mongoid/mongoid_fulltext/actions/workflows/test.yml?query=branch%3Amaster) [![Coverage Status](https://coveralls.io/repos/github/mongoid/mongoid_fulltext/badge.svg?branch=master)](https://coveralls.io/github/mongoid/mongoid_fulltext?branch=master)
7
4
 
8
5
  Full-text search using n-gram matching for the Mongoid ODM.
9
6
 
10
- MongoDB introduced full-text search capabilities in v2.4, so this gem is a good fit for cases where you want something a little less than a full-blown indexing service. The mongoid_fulltext gem
11
- lets you do a fuzzy string search across relatively short strings, which makes it good for populating autocomplete boxes based on the display names of your Rails models but not appropriate for, say, indexing hundreds of thousands of HTML documents.
7
+ CI reports real SimpleCov coverage from the Ruby 4.0 job to Coveralls. Run `COVERAGE=true bundle install` and `COVERAGE=true bundle exec rake spec` to collect coverage locally. Danger runs with the isolated `Gemfile.danger`; PR checks have read-only permissions and a separate workflow publishes the report as a comment.
12
8
 
13
- Install
14
- -------
9
+ MongoDB introduced full-text search capabilities in v2.4, so this gem is a good fit for cases where you want something a little less than a full-blown indexing service. The mongoid_fulltext gem lets you do a fuzzy string search across relatively short strings, which makes it good for populating autocomplete boxes based on the display names of your Rails models but not appropriate for, say, indexing hundreds of thousands of HTML documents.
15
10
 
16
- Version 0.6.1 or newer of this gem requires Ruby 1.9.3 or newer and works with Mongoid 3, 4, 5 and 6, 7.
17
- Use version 0.5.x for Mongoid 2.4.x and Ruby 1.8.7, 1.9.2 or 1.9.3.
18
- For Ruby 1.8.7 and/or Mongoid 2.x use [mongoid_fulltext 0.5.x](https://github.com/mongoid/mongoid_fulltext/tree/0.5-stable).
11
+ ## Install
19
12
 
20
- ``` ruby
13
+ The current CI matrix exercises representative Ruby/Mongoid/MongoDB combinations from Ruby 2.1 and Mongoid 3 through Ruby 4.0, Mongoid 9, and MongoDB 8.0. Use version 0.5.x for Mongoid 2.4.x and Ruby 1.8.7, 1.9.2 or 1.9.3. For Ruby 1.8.7 and/or Mongoid 2.x use [mongoid_fulltext 0.5.x](https://github.com/mongoid/mongoid_fulltext/tree/0.5-stable).
14
+
15
+ ```ruby
21
16
  gem 'mongoid_fulltext'
22
17
  ```
23
18
 
24
- Examples
25
- --------
19
+ ## Examples
26
20
 
27
21
  Suppose you have an `Artist` model and want to index each artist's name:
28
22
 
29
- ``` ruby
23
+ ```ruby
30
24
  class Artist
31
25
  include Mongoid::Document
32
26
  include Mongoid::FullTextSearch
@@ -42,18 +36,15 @@ class Artist
42
36
  end
43
37
  ```
44
38
 
45
- The `fulltext_search_in` directive will index the full name of the artist, so now
46
- you can call:
39
+ The `fulltext_search_in` directive will index the full name of the artist, so now you can call:
47
40
 
48
- ``` ruby
49
- Artist.fulltext_search("vince vangogh")
41
+ ```ruby
42
+ Artist.fulltext_search('vince vangogh')
50
43
  ```
51
44
 
52
- which will return an array of the Artist instances that best match the search string. Most likely,
53
- Vincent van Gogh will be included in the results. You can index multiple fields with the same
54
- index, so we can get the same effect of our Artist index above using:
45
+ which will return an array of the Artist instances that best match the search string. Most likely, Vincent van Gogh will be included in the results. You can index multiple fields with the same index, so we can get the same effect of our Artist index above using:
55
46
 
56
- ``` ruby
47
+ ```ruby
57
48
  class Artist
58
49
  include Mongoid::Document
59
50
  include Mongoid::FullTextSearch
@@ -65,32 +56,52 @@ class Artist
65
56
  end
66
57
  ```
67
58
 
59
+ Array fields containing strings are supported alongside scalar fields, for example `fulltext_search_in :title, :tags` with `field :tags, type: Array`. Each array element is indexed independently, so ngrams do not span tags. Nil and empty elements are ignored; changing or clearing the array replaces its old index entries.
60
+
68
61
  To restrict the number of results returned, pass the `:max_results` parameter to `fulltext_search`:
69
62
 
70
- ``` ruby
71
- Artist.fulltext_search("vince vangogh", { :max_results => 5 })
63
+ ```ruby
64
+ Artist.fulltext_search('vince vangogh', { max_results: 5 })
72
65
  ```
73
66
 
74
67
  To return a pair of `[ result, score ]` instead of an array of results, pass the `:return_scores` parameter to `fulltext_search`:
75
68
 
76
- ``` ruby
77
- Artist.fulltext_search("vince vangogh", { :return_scores => true })
69
+ ```ruby
70
+ Artist.fulltext_search('vince vangogh', { return_scores: true })
78
71
  ```
79
72
 
80
- The larger a score is, the better mongoid_fulltext thinks the match is. The scores have the following rough
81
- interpretation that you can use to make decisions about whether the match is good enough:
73
+ The larger a score is, the better mongoid_fulltext thinks the match is. The scores have the following rough interpretation that you can use to make decisions about whether the match is good enough:
82
74
 
83
- * If a prefix of your query matches something indexed, or if your query matches a prefix of something
84
- indexed (for example, searching for "foo" finds "myfoo" or searching for "myfoo" finds "foo"), you
85
- can expect a score of at least 1 for the match.
86
- * If an entire word in your query matches an entire word that's indexed and you have the `index_full_words`
87
- option turned on (it's turned on by default), you can expect a score of at least 2 for the match.
75
+ * If a prefix of your query matches something indexed, or if your query matches a prefix of something indexed (for example, searching for "foo" finds "myfoo" or searching for "myfoo" finds "foo"), you can expect a score of at least 1 for the match.
76
+ * If an entire word in your query matches an entire word that's indexed and you have the `index_full_words` option turned on (it's turned on by default), you can expect a score of at least 2 for the match.
88
77
  * If neither of the above criteria are met, you can expect a score less than one.
89
78
 
90
- If you don't specify a field to index, the default is the result of `to_s` called on the object.
91
- The following definition will index the first and last name of an artist:
79
+ ### Weighted Fields
80
+
81
+ Use `:priorities` to give matches in some fields more influence on relevance:
82
+
83
+ ```ruby
84
+ fulltext_search_in :title, :description, :tags,
85
+ priorities: { title: 10, description: 5 },
86
+ score_aggregation: :max
87
+ ```
88
+
89
+ Weights must be positive finite numbers; omitted fields have weight 1. Symbol and string field names are accepted, including computed readers and the default `to_s` field. Unknown fields, duplicate symbol/string keys for the same field, invalid weights, and unsupported aggregation modes raise `ArgumentError` when the index is declared.
90
+
91
+ `:score_aggregation` determines how a term shared by multiple fields is scored:
92
+
93
+ * `:max` (the default when `:priorities` is provided) keeps the maximum weighted contribution.
94
+ * `:sum` adds the weighted contributions from different fields.
92
95
 
93
- ``` ruby
96
+ Within an array field, both modes keep the maximum contribution for each term across the elements before applying the field's weight. Repeated tags do not increase relevance. Repeating the same field in the declaration does not count it twice. Set `:score_aggregation` alone to opt into either mode with weight 1 for every field.
97
+
98
+ Weights multiply stored document-term scores only; query-term scoring and candidate limits are unchanged. They apply independently to each locale and work with scalar fields, arrays, computed readers, filters, and shared index collections. Models sharing a collection should use comparable weights if their scores should be comparable.
99
+
100
+ The rough score thresholds above describe unweighted search, not weighted or summed scores. Higher weights or additional matching fields can outweigh a more exact match, and candidate limits still make search approximate. No per-field metadata or additional records are stored.
101
+
102
+ If you don't specify a field to index, the default is the result of `to_s` called on the object. The following definition will index the first and last name of an artist:
103
+
104
+ ```ruby
94
105
  class Artist
95
106
  include Mongoid::Document
96
107
  include Mongoid::FullTextSearch
@@ -99,33 +110,28 @@ class Artist
99
110
  field :last_name
100
111
 
101
112
  def to_s
102
- '%s %s' % [first_name, last_name]
113
+ "#{first_name} #{last_name}"
103
114
  end
104
115
 
105
116
  fulltext_search_in
106
117
  end
107
118
  ```
108
119
 
109
- The full-text index is stored in a separate MongoDB collection in the same database as the
110
- models you're indexing. By default, the name of this collection is generated for you. Above,
111
- a collection named something like `mongoid_fulltext.index_artist_0` will be created to
112
- hold the index data. You can override this naming and provide your own collection name with
113
- the :index_name parameter:
120
+ The full-text index is stored in a separate MongoDB collection in the same database as the models you're indexing. By default, the name of this collection is generated for you. Above, a collection named something like `mongoid_fulltext.index_artist_0` will be created to hold the index data. You can override this naming and provide your own collection name with the :index_name parameter:
114
121
 
115
- ``` ruby
122
+ ```ruby
116
123
  class Artwork
117
124
  include Mongoid::Document
118
125
  include Mongoid::FullTextSearch
119
126
 
120
127
  field :title
121
- fulltext_search_in :title, :index_name => 'mongoid_fulltext.foobar'
128
+ fulltext_search_in :title, index_name: 'mongoid_fulltext.foobar'
122
129
  end
123
130
  ```
124
131
 
125
- You can also create multiple indexes on a single model, in which case you'll want to
126
- provide index names:
132
+ You can also create multiple indexes on a single model, in which case you'll want to provide index names:
127
133
 
128
- ``` ruby
134
+ ```ruby
129
135
  class Artwork
130
136
  include Mongoid::Document
131
137
  include Mongoid::FullTextSearch
@@ -135,36 +141,29 @@ class Artwork
135
141
  field :gallery_name
136
142
  filed :gallery_address
137
143
 
138
- fulltext_search_in :title, :index_name => 'title_index'
139
- fulltext_search_in :artist_name, :index_name => 'artist_name_index'
140
- fulltext_search_in :gallery_name, :gallery_address, :index_name => 'gallery_index'
144
+ fulltext_search_in :title, index_name: 'title_index'
145
+ fulltext_search_in :artist_name, index_name: 'artist_name_index'
146
+ fulltext_search_in :gallery_name, :gallery_address, index_name: 'gallery_index'
141
147
  end
142
148
  ```
143
149
 
144
- The index names are helpful now because you'll have to specify which one you want to use when you
145
- call `fulltext_search`:
150
+ The index names are helpful now because you'll have to specify which one you want to use when you call `fulltext_search`:
146
151
 
147
- ``` ruby
148
- Artwork.fulltext_search('warhol', :index => 'artist_name_index')
152
+ ```ruby
153
+ Artwork.fulltext_search('warhol', index: 'artist_name_index')
149
154
  ```
150
155
 
151
- If you have multiple indexes specified and you don't supply a name to `fulltext_search`, the
152
- method call will raise an exception.
156
+ If you have multiple indexes specified and you don't supply a name to `fulltext_search`, the method call will raise an exception.
153
157
 
154
- If you're indexing multiple models, you may find that you need to combine results to create
155
- a single result set. For example, if both the `Artist` model and the `Artwork` model are
156
- indexed for full-text search, then to get results from both, you'd have to call
157
- `Artist.fulltext_search` and `Artwork.fulltext_search` and combine the results yourself. If
158
- your intention is instead to get the top k results from both Artists and Artworks, you can
159
- merge both into a single index by using the same `:external_index` parameter:
158
+ If you're indexing multiple models, you may find that you need to combine results to create a single result set. For example, if both the `Artist` model and the `Artwork` model are indexed for full-text search, then to get results from both, you'd have to call `Artist.fulltext_search` and `Artwork.fulltext_search` and combine the results yourself. If your intention is instead to get the top k results from both Artists and Artworks, you can merge both into a single index by using the same `:external_index` parameter:
160
159
 
161
- ``` ruby
160
+ ```ruby
162
161
  class Artwork
163
162
  include Mongoid::Document
164
163
  include Mongoid::FullTextSearch
165
164
 
166
165
  field :title
167
- fulltext_search_in :title, :index_name => 'artwork_and_artists'
166
+ fulltext_search_in :title, index_name: 'artwork_and_artists'
168
167
  end
169
168
 
170
169
  class Artist
@@ -172,34 +171,28 @@ class Artist
172
171
  include Mongoid::FullTextSearch
173
172
 
174
173
  field :name
175
- fulltext_search_in :name, :index_name => 'artwork_and_artists'
174
+ fulltext_search_in :name, index_name: 'artwork_and_artists'
176
175
  end
177
176
  ```
178
177
 
179
- Now that these two models share the same external index collection, we can search them both through
180
- either model's `fulltext_search` method:
178
+ Now that these two models share the same external index collection, we can search them both through either model's `fulltext_search` method:
181
179
 
182
- ``` ruby
183
- Artwork.fulltext_search('picasso') # returns same results as Artist.fulltext_search('picasso')
180
+ ```ruby
181
+ Artwork.fulltext_search('picasso') # returns same results as Artist.fulltext_search('picasso')
184
182
  ```
185
183
 
186
- If you want to filter the results from full-text search, you set up filters when the indexes are
187
- defined. For example, suppose that in addition to wanting to use the `artwork_and_artists` index
188
- defined above to search for `Artwork`s or `Artist`s, we want to be able to run full-text searches
189
- for artists only and for artworks priced above $10,000. Instead of creating two new indexes or
190
- attempting to filter the results after the query is run, we can specify the filter predicates
191
- at the time of index definition:
184
+ If you want to filter the results from full-text search, you set up filters when the indexes are defined. For example, suppose that in addition to wanting to use the `artwork_and_artists` index defined above to search for `Artwork` or `Artist` documents, we want to be able to run full-text searches for artists only and for artworks priced above $10,000. Instead of creating two new indexes or attempting to filter the results after the query is run, we can specify the filter predicates at the time of index definition:
192
185
 
193
- ``` ruby
186
+ ```ruby
194
187
  class Artwork
195
188
  include Mongoid::Document
196
189
  include Mongoid::FullTextSearch
197
190
 
198
191
  field :title
199
192
  field :price
200
- fulltext_search_in :title, :index_name => 'artwork_and_artists',
201
- :filters => { :is_expensive => lambda { |x| x.price > 10000 },
202
- :has_long_name => lambda { |x| x.title.length > 20 }}
193
+ fulltext_search_in :title, index_name: 'artwork_and_artists',
194
+ filters: { is_expensive: ->(x) { x.price > 10_000 },
195
+ has_long_name: ->(x) { x.title.length > 20 } }
203
196
  end
204
197
 
205
198
  class Artist
@@ -208,85 +201,95 @@ class Artist
208
201
 
209
202
  field :name
210
203
  field :birth_year
211
- fulltext_search_in :name, :index_name => 'artwork_and_artists',
212
- :filters => { :born_before_1900 => lambda { |x| x.birth_year < 1900 },
213
- :has_long_name => lambda { |x| x.name.length > 20}}
204
+ fulltext_search_in :name, index_name: 'artwork_and_artists',
205
+ filters: { born_before_1900: ->(x) { x.birth_year < 1900 },
206
+ has_long_name: ->(x) { x.name.length > 20 } }
214
207
  end
215
208
  ```
216
209
 
217
210
  After defining filters, you can query for results that match particular values of filters:
218
211
 
219
- ``` ruby
212
+ ```ruby
220
213
  # Only return artists born before 1900 that match 'foobar'
221
- Artist.fulltext_search('foobar', :born_before_1900 => true)
214
+ Artist.fulltext_search('foobar', born_before_1900: true)
222
215
 
223
216
  # Return artists or artworks that match 'foobar' and have short names
224
- Artist.fulltext_search('foobar', :has_long_name => false)
217
+ Artist.fulltext_search('foobar', has_long_name: false)
225
218
 
226
219
  # Only return artworks with prices over 10000 that match 'mona lisa'
227
- Artwork.fulltext_search('mona lisa', :is_expensive => true)
220
+ Artwork.fulltext_search('mona lisa', is_expensive: true)
228
221
 
229
222
  # Only return artworks with prices less than 10000 that match 'mona lisa'
230
- Artwork.fulltext_search('mona lisa', :is_expensive => false)
223
+ Artwork.fulltext_search('mona lisa', is_expensive: false)
231
224
  ```
232
225
 
233
- Note that in all of the example queries above, supplying a filter that is defined on exactly
234
- one of the models will restrict the search to results from that model only. For example,
235
- since `:is_expensive` is defined only on `Artwork`s, a call to `fulltext_search` with either
236
- `:is_expensive => true` or `:is_expensive => false` will return only `Artwork` results.
226
+ Note that in all of the example queries above, supplying a filter that is defined on exactly one of the models will restrict the search to results from that model only. For example, since `:is_expensive` is defined only on `Artwork`, a call to `fulltext_search` with either `:is_expensive => true` or `:is_expensive => false` will return only `Artwork` results.
227
+
228
+ You can specify multiple filters per index and per model. Each filter is a predicate that will be called on objects as they're inserted into the full-text index (any time the model is saved.) Filters are only called on instances of models they're defined on, so in the example above, the `is_expensive` filter is only applied to instances of `Artwork` and the `born_before_1900` filter is only applied to instances of `Artist`, although both filters can be used when querying from either model. The `has_long_name` filter, on the other hand, will return instances of both `Artwork` and `Artist` since it's defined on each model.
229
+
230
+ Filters shouldn't ever throw, but if they do, the filter is just ignored. If you apply filters to indexes that are on multiple fields, the filter is applied to each field and the filter result is the AND of all of the individual results for each of the fields. Finally, if a filter is defined but criteria for that filter aren't passed to `fulltext_search`, the result is as if the filter had never been defined - you see both models that both pass and fail the filter in the results.
231
+
232
+ ## Indexing Options
233
+
234
+ `Artwork.update_ngram_index(timeout: false)` rebuilds the index for all records without a cursor timeout; the `timeout` option belongs to the class method, not the per-document `artwork.update_ngram_index` method.
237
235
 
238
- You can specify multiple filters per index and per model. Each filter is a predicate that will
239
- be called on objects as they're inserted into the full-text index (any time the model is saved.)
240
- Filters are only called on instances of models they're defined on, so in the example above, the
241
- `is_expensive` filter is only applied to instances of `Artwork` and the `born_before_1900` filter
242
- is only applied to instances of `Artist`, although both filters can be used when querying from
243
- either model. The `has_long_name` filter, on the other hand, will return instances of both
244
- `Artwork` and `Artist` since it's defined on each model.
236
+ `Artwork.create_indexes` can create the full-text collections and their indexes before any artworks have been saved.
245
237
 
246
- Filters shouldn't ever throw, but if they do, the filter is just ignored. If you apply filters to
247
- indexes that are on multiple fields, the filter is applied to each field and the filter result is
248
- the AND of all of the individual results for each of the fields. Finally, if a filter is defined
249
- but criteria for that filter aren't passed to `fulltext_search`, the result is as if the filter
250
- had never been defined - you see both models that both pass and fail the filter in the results.
238
+ Localized Mongoid fields (`field :title, type: String, localize: true`) are indexed for every locale in `I18n.available_locales`. Declare the field normally with `fulltext_search_in :title`; searches use `I18n.locale`, so use `I18n.with_locale(:cs) { Artwork.fulltext_search('obraz') }` to search a particular translation. Field readers, computed methods, `update_if`, and filters run within each locale, honoring Mongoid's configured fallback behavior. This does not search all languages at once.
251
239
 
252
- Indexing Options
253
- ----------------
240
+ All translations use the original full-text index collection. Each ngram record for an index that explicitly includes a localized field has a string `locale` value, for example `{ document_id: id, locale: 'cs', ngram: 'obr', score: score, class: 'Artwork' }`. Searches filter by locale, backed by a compound index beginning with `locale`, `ngram`, and `score`. Nonlocalized index records remain unchanged. Models sharing a localized index must all include a localized field in that index and use the same locale configuration. Define available locales before indexing and rebuild after adding a locale. The alphabet must still contain the characters being indexed. Existing localized-field users must follow [UPGRADING](UPGRADING.md) to rebuild locale-tagged records.
241
+
242
+ Searches can be prefixed with Mongoid criteria, for example `Artwork.where(published: true).fulltext_search('flowers', max_results: 5)`. The result remains an array in relevance order, not a chainable criteria; ordering and pagination on the preceding criteria are not a substitute for sorting or paginating that array. Excluded or deleted documents are skipped before applying `max_results`, within the existing candidate-set bound.
243
+
244
+ Single-collection inheritance is respected: a root-class search includes its descendants, while a subclass search excludes its parent and siblings. An unscoped search of an index shared by unrelated models still returns all those models. Adding criteria restricts the results to the calling model and its descendants. Existing index records already contain the class name, so no reindex is required.
245
+
246
+ The default `alphabet` only includes ASCII letters, digits, and spaces. Use a Unicode-aware regular expression to support whole scripts without enumerating their characters. For example, `/\p{Han}/` accepts Han characters, including those used in Chinese:
247
+
248
+ ```ruby
249
+ class ChineseArtwork
250
+ include Mongoid::Document
251
+ include Mongoid::FullTextSearch
252
+
253
+ field :title, type: String
254
+ fulltext_search_in :title, alphabet: /\p{Han}/, ngram_width: 2
255
+ end
256
+
257
+ artwork = ChineseArtwork.create!(title: "\u5367\u864e\u85cf\u9f99")
258
+ ChineseArtwork.fulltext_search("\u85cf\u9f99") # => [artwork]
259
+ ```
260
+
261
+ For multilingual text, use `alphabet: /[\p{L}\p{M}\p{N}]/` to accept Unicode letters, combining marks, and numbers, or `/[\p{Latin}\p{Cyrillic}]/` to restrict letters to those scripts. Existing string allowlists remain supported and the ASCII default is unchanged.
262
+
263
+ The expression is tested against each character after accent normalization and lowercasing, not against whole words. Configured word separators are retained independently of the alphabet; other unmatched characters are discarded. `remove_accents: false` preserves combining marks and accents when needed. This is character-ngram matching, not language-aware word segmentation. A shorter `ngram_width` helps with short search terms. Changing the alphabet or ngram width requires rebuilding existing indexes with `ChineseArtwork.update_ngram_index`. Configuring the alphabet is separate from indexing Mongoid localized fields.
264
+
265
+ Each document update submits its ngrams as a single bulk insert per nonempty full-text index and locale. The MongoDB driver may split very large batches to meet server limits. Empty indexes are cleared without preventing later indexes on the same model from being updated. Index replacement is not atomic.
254
266
 
255
267
  Additional indexing/query options can be used as parameters to `fulltext_search_in`.
256
268
 
257
- * `alphabet`: letters to index, default is `abcdefghijklmnopqrstuvwxyz0123456789 `.
269
+ * `alphabet`: a string allowlist or a regular expression matched against each character, default is `abcdefghijklmnopqrstuvwxyz0123456789` and a space.
258
270
  * `word_separators`: word separators, default is the space character.
259
271
  * `ngram_width`: ngram width, default is `3`.
260
272
  * `index_full_words`: index full words, which improves exact matches, default is `true`.
261
- * `index_short_prefixes`: index a prefix of each full word of length `(ngram_width-1)`. Useful if
262
- you use a larger ngram_width than the default of 3. Default for this option is `false`.
263
- * `stop_words`: a hash of words to avoid indexing as full words. Used only if `index_full_words`
264
- is set to `true`. Defaults to a hash containing a list of common English stop words.
273
+ * `index_short_prefixes`: index a prefix of each full word of length `(ngram_width-1)`. Useful if you use a larger ngram_width than the default of 3. Default for this option is `false`.
274
+ * `stop_words`: a hash of words to avoid indexing as full words. Used only if `index_full_words` is set to `true`. Defaults to a hash containing a list of common English stop words.
265
275
  * `apply_prefix_scoring_to_all_words`: score n-grams at beginning of words higher, default is `true`.
266
- * `max_ngrams_to_search`: maximum number of ngrams to query at any given time, default is `6`.
267
- * `max_candidate_set_size`: maximum number of candidate ngrams to examine for a given query.
268
- Defaults to 1000. If you're seeing poor results, you can try increasing this value to consider
269
- more ngrams per query (changing this parameter does not require a re-index.) The amount of time
270
- a search takes is directly proportional to this parameter's value.
271
- * `remove_accents`: remove accents on accented characters, default is `true`.
272
- We strip the accents using [NFKD normalization](http://unicode-utils.rubyforge.org/UnicodeUtils.html#method-c-compatibility_decomposition)
273
- using an external library, `unicode_utils`.
274
- * `update_if`: controls whether or not the index will be updated. This can be set to a symbol,
275
- string, or proc. If the result of evaluating the value is true, the index will be updated.
276
- * When set to a symbol, the symbol is sent to the document.
277
- * When set to a string, the string is evaluated within the document's instance.
278
- * When set to a proc, the proc is called, and the document is given to the proc as the first arg.
279
- * When set to any other type of object, the document's index will not be updated.
276
+ * `max_ngrams_to_search`: positive integer limiting sampled sliding-window ngrams, default is `6`. Samples span the query including the first and last windows when at least two are selected; a limit of one selects the first window. Full-word and short-prefix bonuses are added separately and may increase the total number of queried terms.
277
+ * `max_candidate_set_size`: maximum number of candidate ngrams to examine for a given query. Defaults to 1000. If you're seeing poor results, you can try increasing this value to consider more ngrams per query (changing this parameter does not require a re-index.) The amount of time a search takes is directly proportional to this parameter's value.
278
+ * `remove_accents`: remove accents on accented characters, default is `true`. We strip the accents using [NFKD normalization](https://www.rubydoc.info/gems/unicode_utils/UnicodeUtils.compatibility_decomposition) using an external library, `unicode_utils`.
279
+ * `update_if`: controls whether or not the index will be updated. This can be set to a symbol, string, or proc. If the result of evaluating the value is true, the index will be updated.
280
+ * When set to a symbol, the symbol is sent to the document.
281
+ * When set to a string, the string is evaluated within the document's instance.
282
+ * When set to a proc, the proc is called, and the document is given to the proc as the first arg.
283
+ * When set to any other type of object, the document's index will not be updated.
280
284
  * `reindex_immediately`: whether models will be reindexed automatically upon saves or updates. Defaults to true. When set to false, the class-level `update_ngram_index` method can be called to perform reindexing.
281
285
 
282
- If you work with Cyrillic texts, use this option: `:alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789абвгдежзиклмнопрстуфхцчшщъыьэюя'`.
286
+ For Cyrillic and Latin text with numbers, use `alphabet: /[\p{Latin}\p{Cyrillic}\p{N}]/`.
283
287
 
284
- Array filters
285
- -------------
288
+ ## Array Filters
286
289
 
287
290
  A filter may also return an Array. Consider the following example.
288
291
 
289
- ``` ruby
292
+ ```ruby
290
293
  class Artist
291
294
  include Mongoid::Document
292
295
  include Mongoid::FullTextSearch
@@ -294,106 +297,96 @@ class Artist
294
297
  field :name
295
298
  field :exhibitions, as: Array, default: []
296
299
 
297
- fulltext_search_in :name, :index_name => 'exhibited_artist',
298
- :filters => {
299
- :exhibitions => lambda { |artist| artist.exhibitions }
300
- }
300
+ fulltext_search_in :name, index_name: 'exhibited_artist',
301
+ filters: {
302
+ exhibitions: ->(artist) { artist.exhibitions }
303
+ }
301
304
  end
302
305
  ```
303
306
 
304
- You can now find all artists that are at the Art Basel exhibition or all artists that have exhibited
305
- at both the Art Basel and the New York Armory exhibition.
307
+ You can now find all artists that are at the Art Basel exhibition or all artists that have exhibited at both the Art Basel and the New York Armory exhibition.
306
308
 
307
- ``` ruby
309
+ ```ruby
308
310
  # All artists
309
311
  Artist.fulltext_search('foobar')
310
312
 
311
313
  # Artists at the Art Basel exhibition only
312
- Artist.fulltext_search('foobar', :exhibitions => [ "Art Basel" ])
314
+ Artist.fulltext_search('foobar', exhibitions: ['Art Basel'])
313
315
 
314
316
  # Artists at both the Art Basel and the New York Armory exhibition
315
- Artist.fulltext_search('foobar', :exhibitions => [ "Art Basel", "New York Armory" ])
317
+ Artist.fulltext_search('foobar', exhibitions: ['Art Basel', 'New York Armory'])
316
318
 
317
319
  # Note that the following explicit syntax may be used to achieve the
318
320
  # same result as above
319
- Artist.fulltext_search('foobar', :exhibitions => {:all => [ "Art Basel", "New York Armory" ]})
321
+ Artist.fulltext_search('foobar', exhibitions: { all: ['Art Basel', 'New York Armory'] })
320
322
  ```
321
323
 
322
- If you want to find all artists that are at either the Art Basel or the
323
- New York Armory exhibition, then you may specify the `:any` operator in
324
- the filter.
324
+ If you want to find all artists that are at either the Art Basel or the New York Armory exhibition, then you may specify the `:any` operator in the filter.
325
325
 
326
- ``` ruby
326
+ ```ruby
327
327
  # Artists at either the Art Basel or the New York Armory exhibition
328
- Artist.fulltext_search('foobar', :exhibitions => {:any => [ "Art Basel", "New York Armory" ]})
328
+ Artist.fulltext_search('foobar', exhibitions: { any: ['Art Basel', 'New York Armory'] })
329
329
  ```
330
330
 
331
- Note that `:all` and `:any` are currently the only supported operators
332
- for the array filters.
331
+ Note that `:all` and `:any` are currently the only supported operators for the array filters.
333
332
 
334
- Building the index
335
- ------------------
333
+ ## Building the Index
336
334
 
337
- The fulltext index is built and maintained incrementally by hooking into `before_save` and
338
- `before_destroy` callbacks on each model that's being indexed. If you want to build an index
339
- on existing models, you can call the `update_ngram_index` method on the class or each instance:
335
+ The fulltext index is built and maintained incrementally by hooking into `before_save` and `before_destroy` callbacks on each model that's being indexed. If you want to build an index on existing models, you can call the `update_ngram_index` method on the class or each instance:
340
336
 
341
- ``` ruby
337
+ ```ruby
342
338
  Artwork.update_ngram_index
343
339
  Artwork.find(id).update_ngram_index
344
340
  ```
345
341
 
346
- You can remove all or individual instances from the index with the `remove_from_ngram_index`
347
- method:
342
+ If you need to update the index for a large number of documents, using the option below will disable your query from timing out:
343
+
344
+ ```ruby
345
+ Artwork.update_ngram_index(timeout: false)
346
+ ```
347
+
348
+ You can remove all or individual instances from the index with the `remove_from_ngram_index` method:
348
349
 
349
- ``` ruby
350
+ ```ruby
350
351
  Artwork.remove_from_ngram_index
351
352
  Artwork.find(id).remove_from_ngram_index
352
353
  ```
353
354
 
354
- The methods on the model level perform bulk removal operations and are therefore faster that
355
- updating or removing records individually.
355
+ The methods on the model level perform bulk removal operations and are therefore faster that updating or removing records individually.
356
356
 
357
- If you need to control when the index is updated, provide the `update_if` option to
358
- `fulltext_search_in`, and set it to a symbol, string, or proc. Eg:
357
+ If you need to control when the index is updated, provide the `update_if` option to `fulltext_search_in`, and set it to a symbol, string, or proc. Eg:
359
358
 
360
- ``` ruby
359
+ ```ruby
361
360
  # Only update the "age" index if the "age" field has changed.
362
- fulltext_search_in :age, :update_if => :age_changed?
361
+ fulltext_search_in :age, update_if: :age_changed?
363
362
 
364
363
  # Only update the "names" index if the "firstname" or "lastname" field has changed.
365
- fulltext_search_in :names, :update_if => "firstname_changed? || lastname_changed?"
364
+ fulltext_search_in :names, update_if: 'firstname_changed? || lastname_changed?'
366
365
 
367
366
  # Only update the "email" index if the "email" field ends with "gmail.com".
368
- fulltext_search_in :email, :update_if => Proc.new { |doc| doc.email.match /gmail.com\Z/ }
367
+ fulltext_search_in :email, update_if: proc { |doc| doc.email.match(/gmail.com\Z/) }
369
368
  ```
370
369
 
371
- Mongo Database Indexes
372
- ----------------------
370
+ ## Mongo Database Indexes
373
371
 
374
- Mongoid provides an indexing mechanism on its models triggered by the `create_indexes` method.
375
- Mongoid_fulltext will hook into that behavior and create appropriate database indexes on its
376
- collections. These indexes are required for an efficient full text search.
372
+ Mongoid provides an indexing mechanism on its models triggered by the `create_indexes` method. Mongoid_fulltext will hook into that behavior and create appropriate database indexes on its collections. These indexes are required for an efficient full text search.
377
373
 
378
374
  Creating database indexes is typically done with the `db:mongoid:create_indexes` task.
379
375
 
380
- ``` bash
376
+ ```bash
381
377
  rake db:mongoid:create_indexes
382
378
  ```
383
379
 
384
- Running the specs
385
- -----------------
380
+ ## Running the Specs
386
381
 
387
382
  To run the specs, execute `rake spec`. You need a local MongoDB instance to run the specs.
388
383
 
389
- Contributing
390
- ------------
384
+ ## Contributing
391
385
 
392
- Fork the project. Make your feature addition or bug fix with tests. Send a pull request. Bonus points for topic branches.
386
+ See [CHANGELOG.md](CHANGELOG.md), [UPGRADING.md](UPGRADING.md), and [RELEASING.md](RELEASING.md).
393
387
 
394
- Copyright and License
395
- ---------------------
388
+ ## Copyright and License
396
389
 
397
390
  MIT License, see [LICENSE](LICENSE) for details.
398
391
 
399
- (c) 2011-2017 [Artsy Inc.](http://artsy.github.io)
392
+ (c) 2011-2017 [Artsy Inc.](https://artsy.github.io)