solr ClientUtils转义特殊字符

使用solr搜索时,如果要查询的字段值中含有+ - ^等特殊字符时,我们可以使用solr自带的ClientUtils.escapeQueryChars("特殊字符的字符串")进行转义,否则会报错,其中可以转义的字符有

'\\'  '+'  '-'  '!'   '('  ')'  ':'     '^'  '['  ']'  '\"'  '{'   '}'   '~'

          '*'  '?'  '|'   '&'    ';'     '/'      和空白串

源码如下:

public static String escapeQueryChars(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 == ';' || c == '/'

        || Character.isWhitespace(c)) {

        sb.append('\\');

      }

      sb.append(c);

    }

    return sb.toString();

  }

猜你喜欢

转载自shareisattitude.iteye.com/blog/2202819
今日推荐