Commit 4efa577e4fa349e2b3ff68bfee42932a7fd6faf5
1 parent
4f1c9882
Exists in
master
and in
17 other branches
Fixed anchored regular expressions and added warnings for certain regular expressions
Showing
3 changed files
with
36 additions
and
3 deletions
Show diff stats
CHANGELOG.md
lib/searchkick/query.rb
... | ... | @@ -985,7 +985,20 @@ module Searchkick |
985 | 985 | elsif value.nil? |
986 | 986 | {bool: {must_not: {exists: {field: field}}}} |
987 | 987 | elsif value.is_a?(Regexp) |
988 | - {regexp: {field => {value: value.source, flags: "NONE"}}} | |
988 | + if value.casefold? | |
989 | + warn "[searchkick] Case-insensitive flag does not work with Elasticsearch" | |
990 | + end | |
991 | + | |
992 | + source = value.source | |
993 | + unless source.start_with?("\\A") && source.end_with?("\\z") | |
994 | + # https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html | |
995 | + warn "[searchkick] Regular expressions are always anchored in Elasticsearch" | |
996 | + end | |
997 | + | |
998 | + # remove \A and \z | |
999 | + source = source.sub(/\\A/, "").sub(/\\z\z/, "") | |
1000 | + | |
1001 | + {regexp: {field => {value: source, flags: "NONE"}}} | |
989 | 1002 | else |
990 | 1003 | {term: {field => value}} |
991 | 1004 | end | ... | ... |
test/where_test.rb
... | ... | @@ -78,7 +78,7 @@ class WhereTest < Minitest::Test |
78 | 78 | |
79 | 79 | def test_regexp |
80 | 80 | store_names ["Product A"] |
81 | - assert_search "*", ["Product A"], where: {name: /Pro.+/} | |
81 | + assert_search "*", ["Product A"], where: {name: /\APro.+\z/} | |
82 | 82 | end |
83 | 83 | |
84 | 84 | def test_alternate_regexp |
... | ... | @@ -88,7 +88,22 @@ class WhereTest < Minitest::Test |
88 | 88 | |
89 | 89 | def test_special_regexp |
90 | 90 | store_names ["Product <A>", "Item <B>"] |
91 | - assert_search "*", ["Product <A>"], where: {name: /Pro.+<.+/} | |
91 | + assert_search "*", ["Product <A>"], where: {name: /\APro.+<.+\z/} | |
92 | + end | |
93 | + | |
94 | + # regular expressions are always anchored in ES | |
95 | + def test_regexp_not_anchored | |
96 | + store_names ["abcde"] | |
97 | + assert_search "*", [], where: {name: /abcd/} | |
98 | + assert_search "*", ["abcde"], where: {name: /abcde/} | |
99 | + assert_search "*", ["abcde"], where: {name: /\Aabcde\z/} | |
100 | + end | |
101 | + | |
102 | + def test_regexp_case | |
103 | + store_names ["abcde"] | |
104 | + assert_search "*", [], where: {name: /\AABCDE\z/} | |
105 | + # flags don't work | |
106 | + assert_search "*", [], where: {name: /\AABCDE\z/i} | |
92 | 107 | end |
93 | 108 | |
94 | 109 | def test_prefix | ... | ... |