ES7默认自带了中文分词,根据实际情况,可自选择配置分词策略
//1、索引库
SearchRequest searchRequest = new SearchRequest("resource");
//2、查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
//资源类型type是精确匹配
.must(QueryBuilders.termQuery("type", type));
if(StringUtils.isNotEmpty(code)) {
//树编码是前缀匹配
boolQueryBuilder.must(QueryBuilders.matchPhrasePrefixQuery("code", code));
}
boolean havKeywords = StringUtils.isNotEmpty(keywords);
if(havKeywords) {
//关键字多字段分词匹配:搜索范围字段(分词)
String[] searchFields = {"name","pName","source","scope","desc","fieldNames"};
BoolQueryBuilder boolQueryBuilder2 = QueryBuilders.boolQuery()
.should(QueryBuilders.multiMatchQuery(keywords, searchFields));
boolQueryBuilder.must(boolQueryBuilder2);
//3、设置高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name");
highlightBuilder.field("pName");
highlightBuilder.field("source");
highlightBuilder.field("scope");
highlightBuilder.field("desc");
highlightBuilder.field("fieldNames");
//设置高亮前置标签,设置红色
highlightBuilder.preTags("<span style='color:red'>");
//设置高亮后置标签
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
}
//排序 2审批时间排序
if(sortType == 2) {
searchSourceBuilder.sort("approvalTime.keyword",SortOrder.DESC);
}
//3、执行查询
searchSourceBuilder.query(boolQueryBuilder);
searchSourceBuilder.from(from);
searchSourceBuilder.size(size);
searchSourceBuilder.timeout(new TimeValue(10000));
searchSourceBuilder.trackTotalHits(true);
searchRequest.source(searchSourceBuilder);
try {
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//通过发送初始搜索请求来初始化搜索上下文
searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
map.put("total",searchResponse.getHits().getTotalHits().value);
SearchHit[] rows = searchResponse.getHits().getHits();
for(SearchHit row : rows) {
Map<String,Object> rowMap = row.getSourceAsMap();
Map<String, HighlightField> highlightFields = row.getHighlightFields();
rowMap.put("fieldNames", "");
for(String highlightField : highlightFields.keySet()) {
//高亮值,默认取第一个即可
String val = highlightFields.get(highlightField).getFragments()[0].toString();
if("fieldNames".equals(highlightField)) {
//有关键字输入才查询返回该字段
if(havKeywords) {
String[] fieldVals = val.split(",");
List<String> resultFields = new ArrayList<String>();
for(String field : fieldVals) {
if(field.contains("</span>")) {
resultFields.add(field);
}
}
val = StringUtils.join(resultFields.toArray(), ",");
rowMap.put(highlightField, val);
}
}
rowMap.put(highlightField, val);
}
list.add(rowMap);
}
map.put("list",list);