特别注意:es的模糊查询,只支持keyword;之前踩过的坑,使用正则的方式模糊查询(QueryBuilders.regexpQuery("name.keyword", ".*" + student.getName() + ".*")),遇到特殊符号比如 \ 斜杠,英文的""引号,则匹配不上。
最终总结如下方法可匹配任意字符的模糊查询,可供参考:文章来源:https://www.toymoban.com/news/detail-506592.html
private static final Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
----------------------------------------------------------------
//简单的例子:这里是分页查询,按学生名字模糊查询,然后按添加时间倒序
public NativeSearchQuery getSearchQuery(Student student, Pageable pageRequest){
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.filter(QueryBuilders.wildcarQuery("name.keyword", "*" + this.unicodeToString(student.getName()) + "*")));
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
return nativeSearchQueryBuilder
.withQuery(queryBuilder)
.withSort(SortBuilders.fieldSort("addTime").order(SortOrder.DESC))
.withPageable(pageRequest)
.build();
}
----------------------------------------------------------------
private String unicodeToString (String str){
//将字符串转义
str = StringEscapeUtils.escapeJava(str);
//将Unicode编码格式转化为中文
Match match = pattern.matcher(str);
char ch;
while(matcher.find()){
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
}文章来源地址https://www.toymoban.com/news/detail-506592.html
到了这里,关于es模糊查询的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!