ElasticSearch 5.X 搜索并用高亮显示

时间:2021-08-18 15:11:15

public List<WOSearchModel> searchOrder(OrderSearchReqVO request) throws Exception{
List<WOSearchModel> woSearchModels = new ArrayList<>();

//设置高亮显示
 HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
highlightBuilder.preTags(EagleConst.PRE_TAGS);
highlightBuilder.postTags(EagleConst.POST_TAGS);

//搜索title和orperator和detail
//TODO: 搜索项目名称
QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder(request.getKeyWord());
queryBuilder.analyzer(EagleConst.ES_ANALYSER);
queryBuilder.field(EagleConst.ORDER_TITLE).field(EagleConst.ORDER_OPERATOR).field(EagleConst.ORDER_DETAIL);

//搜索
SearchRequestBuilder searchRequestBuilder = eagleTcpClient.getClient().prepareSearch(EagleConst.INDEX)
.setFrom(request.getStart())
.setSize(request.getSize())
.setTypes(EagleConst.TYPE)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//.setQuery(builder)
.setQuery(queryBuilder)
.highlighter(highlightBuilder)
.setExplain(true); //设置是否按查询匹配度排序
SearchResponse searchResponse = searchRequestBuilder.get();

//获取搜索结果
SearchHits searchHits = searchResponse.getHits();

SearchHit[] hits = searchHits.getHits();
if (hits != null && hits.length != 0){
for (SearchHit hit : hits) {
List<String> highLights = new ArrayList<>();
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
Map<String, Object> source = hit.getSource();
//处理高亮 获取高亮字符串
if (highlightFields != null && highlightFields.size() != 0){
String[] needHighLightFields = new String[]{EagleConst.ORDER_TITLE, EagleConst.ORDER_DETAIL, EagleConst.ORDER_OPERATOR};
for (String needHighLightField : needHighLightFields){
HighlightField titleField = highlightFields.get(needHighLightField);
if(titleField != null){
Text[] fragments = titleField.fragments();
if (fragments != null && fragments.length != 0){
StringBuilder name = new StringBuilder();
for (Text text : fragments) {
name.append(text);
}
source.put(needHighLightField, name.toString());
highLights.add(needHighLightField + ":" + name.toString());
}
}
}
}
WOSearchModel woSearchModel = new WOSearchModel();
woSearchModel.setHighLightTexts(highLights);
OrderModel orderModel = new OrderModel();
BeanUtils.populate(orderModel, source);
woSearchModel.setModel(orderModel);
StringBuilder urlStringBuilder = new StringBuilder();
urlStringBuilder.append(EagleConst.URL_PRE).append("ids=").append(orderModel.getId())
.append("&tenantId=").append(orderModel.getTenantId()).append("&projectId=").append(orderModel.getProjectId());
woSearchModel.setUrl(urlStringBuilder.toString());
woSearchModels.add(woSearchModel);
}
}

return woSearchModels;
}