Thursday, September 29, 2011

Escaping Special Characters And White Space in SOLR in java

Escape Special characters in SOLR before Query
here is the function to escape the culprits

public static String escapeQueryCulprits(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
// These characters are part of the query syntax and must be escaped
if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
|| c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
|| c == '*' || c == '?' || c == '|' || c == '&' || c == ';'
)
{
sb.append('\\');
}
if(Character.isWhitespace(c))
{
sb.append(" \\ ");
}
sb.append(c);
}
return sb.toString();
}

No comments:

About Me