SpringBoot整合ElasticSearch 获取高亮以及最佳片段信息代码实现
从网上找了个遍,没找到一份完整的参考代码,只能自己debug,以及底层代码研究,以及结构研究,撸了出来,分享下;
第一步 数据准备
{
"settings": {
"index.analysis.analyzer.default.type": "ik_max_word"
},
"mappings": {
"my": {
"properties": {
"id": {
"type": "long"
},
"name": {
"type": "text"
},
"content": {
"type": "text"
}
}
}
}
}
建议映射;
然后搞点数据进去;
第二步:依赖引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
这样我们就可以直接 用 ElasticsearchTemplate
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
第三步:最关键的一些接口的研究;
比如QueryBuilder构建,NativeSearchQuery构建,NativeSearchQuery构建的时候,高亮的字段,以后高亮前后缀;
最后是调用ElasticsearchTemplate的queryForPage方法;
匿名内部类:new SearchResultMapper()
来实现 数据回调,得到我们需要的高亮数据,最佳片段信息;包括原始数据;
直接上代码;
@Override public List<ArticleInfo> search(Integer page, Integer pageSize, String searchContent) { BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery() .should(QueryBuilders.matchQuery("name",searchContent)) .should(QueryBuilders.matchQuery("content",searchContent)); NativeSearchQuery nativeSearchQuery=new NativeSearchQueryBuilder() .withQuery(boolQueryBuilder) .withHighlightFields(new HighlightBuilder.Field("content"),new HighlightBuilder.Field("name")) .withHighlightBuilder(new HighlightBuilder().preTags("<span style='color:red'>").postTags("</span>")).build(); AggregatedPage<ArticleInfo> articleInfos = elasticsearchTemplate.queryForPage(nativeSearchQuery, ArticleInfo.class, new SearchResultMapper() { @Override public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { ArrayList<ArticleInfo> articleInfos = new ArrayList<ArticleInfo>(); SearchHits hits = response.getHits(); for (SearchHit searchHit : hits) { if (hits.getHits().length <= 0) { return null; } Map<String, Object> sourceAsMap = searchHit.getSourceAsMap(); String name= (String) sourceAsMap.get("name"); String content= (String) sourceAsMap.get("content"); String id= (String) sourceAsMap.get("id"); System.out.println(name); System.out.println(content); ArticleInfo articleInfo = new ArticleInfo(); HighlightField contentHighlightField = searchHit.getHighlightFields().get("content"); if(contentHighlightField==null){ articleInfo.setContent(content); }else{ String highLightMessage = searchHit.getHighlightFields().get("content").fragments()[0].toString(); articleInfo.setContent(StringUtil.stripHtml(highLightMessage).replaceAll("_","")); } HighlightField nameHighlightField =searchHit.getHighlightFields().get("name"); if(nameHighlightField==null){ articleInfo.setName(name); }else{ articleInfo.setName(searchHit.getHighlightFields().get("name").fragments()[0].toString()); } articleInfo.setId(Long.valueOf(id)); articleInfos.add(articleInfo); } if (articleInfos.size() > 0) { return new AggregatedPageImpl<T>((List<T>) articleInfos); } return null; } }); return articleInfos.getContent();
大伙可以参考;
执行:
这样,才达到了理想的效果;
这个是Java1234 006 百度云搜索引擎需要用到的技术;顺便来点截图,加班加点,春节前尽可能的把屌丝版发布出来,高级版,年后慢慢来;