Created
October 23, 2017 15:57
-
-
Save anveo/2f787d476d9d7d1bf0694aea1eb72e21 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sanitize(str) | |
# https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters | |
escaped_characters = Regexp.escape('\\+-&|!(){}[]^~*?:') | |
str = str.gsub(/([#{escaped_characters}])/, '\\\\\1') | |
# AND, OR and NOT are used by lucene as logical operators. | |
['AND', 'OR', 'NOT'].each do |word| | |
escaped_word = word.split('').map {|char| "\\#{char}" }.join('') | |
str = str.gsub(/\s*\b(#{word.upcase})\b\s*/, " #{escaped_word} ") | |
end | |
# Escape odd quotes | |
quote_count = str.count '"' | |
str = str.gsub(/(.*)"(.*)/, '\1\"\3') if quote_count % 2 == 1 | |
str | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment