Commit 85b7b4cb1a4e7a8426f3c82001655a7e07d3bf24

Authored by Andrew Kane
1 parent 37b7f911

Fixed exclude option with word_start - closes #874

CHANGELOG.md
... ... @@ -2,6 +2,7 @@
2 2  
3 3 - Fixed bug with text values longer than 256 characters and `_all` field - see [#850](https://github.com/ankane/searchkick/issues/850)
4 4 - Fixed issue with `_all` field in `searchable`
  5 +- Fixed `exclude` option with `word_start`
5 6  
6 7 ## 2.1.1
7 8  
... ...
lib/searchkick/query.rb
... ... @@ -283,18 +283,22 @@ module Searchkick
283 283  
284 284 shared_options[:operator] = operator if match_type == :match
285 285  
  286 + exclude_analyzer = nil
  287 +
286 288 if field == "_all" || field.end_with?(".analyzed")
287 289 shared_options[:cutoff_frequency] = 0.001 unless operator == "and" || misspellings == false
288 290 qs.concat [
289 291 shared_options.merge(analyzer: "searchkick_search"),
290 292 shared_options.merge(analyzer: "searchkick_search2")
291 293 ]
  294 + exclude_analyzer = "searchkick_search2"
292 295 elsif field.end_with?(".exact")
293 296 f = field.split(".")[0..-2].join(".")
294 297 queries_to_add << {match: {f => shared_options.merge(analyzer: "keyword")}}
295 298 else
296 299 analyzer = field =~ /\.word_(start|middle|end)\z/ ? "searchkick_word_search" : "searchkick_autocomplete_search"
297 300 qs << shared_options.merge(analyzer: analyzer)
  301 + exclude_analyzer = analyzer
298 302 end
299 303  
300 304 if misspellings != false && match_type == :match
... ... @@ -319,12 +323,15 @@ module Searchkick
319 323 queries_to_add.concat(q2)
320 324 end
321 325  
322   - if options[:exclude]
  326 + if options[:exclude] && exclude_analyzer
323 327 must_not =
324 328 options[:exclude].map do |phrase|
325 329 {
326 330 match_phrase: {
327   - field => phrase
  331 + field => {
  332 + query: phrase,
  333 + analyzer: exclude_analyzer
  334 + }
328 335 }
329 336 }
330 337 end
... ...
test/match_test.rb
... ... @@ -161,21 +161,26 @@ class MatchTest &lt; Minitest::Test
161 161  
162 162 # butter
163 163  
164   - def test_butter
  164 + def test_exclude_butter
165 165 store_names ["Butter Tub", "Peanut Butter Tub"]
166 166 assert_search "butter", ["Butter Tub"], exclude: ["peanut butter"]
167 167 end
168 168  
169   - def test_butter_word_start
  169 + def test_exclude_butter_word_start
170 170 store_names ["Butter Tub", "Peanut Butter Tub"]
171 171 assert_search "butter", ["Butter Tub"], exclude: ["peanut butter"], match: :word_start
172 172 end
173 173  
174   - def test_butter_exact
  174 + def test_exclude_butter_exact
175 175 store_names ["Butter Tub", "Peanut Butter Tub"]
176 176 assert_search "butter", [], exclude: ["peanut butter"], match: :exact
177 177 end
178 178  
  179 + def test_exclude_egg_word_start
  180 + store_names ["eggs", "eggplant"]
  181 + assert_search "egg", ["eggs"], exclude: ["eggplant"], match: :word_start
  182 + end
  183 +
179 184 # other
180 185  
181 186 def test_all
... ...