Skip to content

Instantly share code, notes, and snippets.

@Slakah
Last active September 22, 2020 17:26
Show Gist options
  • Save Slakah/6d02947b2ba528a36dc84fd0544e278d to your computer and use it in GitHub Desktop.
Save Slakah/6d02947b2ba528a36dc84fd0544e278d to your computer and use it in GitHub Desktop.
Scala implementation of lucene escaping, useful when querying elasticsearch
// https://github.com/apache/lucene-solr/blob/master/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java#L973
def luceneEscape(s: String): String = {
// use string builder, as it's probably more efficient
val sb = new StringBuilder
s.foreach {
case char @ ('\\' | '+' | '-' | '!' | '(' | ')' | ':' | '^' | '[' | ']' | '\"' | '{' | '}' | '~' | '*' | '?' | '|' | '&' | '/') =>
sb.append('\\').append(char)
case other => sb.append(other)
}
sb.result()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment