我们当我们在springboot中使用es时首先导入pom包,网上很多说要加很多的其实可以不用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
在我们第一次使用es时,我们想办法吧数据连接到es
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")));
return client;
}
首先确定自己的数据,我这里是从京东爬下来的,我们将数据保存到es,在这之中因为es的都是json数据,所以我们需要对我们的数据进行处理
<!-- jSoup 解析网页 tiko 解析电影-->
<!-- 解析网页-->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
下面就是把我们的数据保存到es之中,这里是我们的service层
public Boolean parseContent(String keywords) throws Exception {
List<Content> contents = new HtmlParseUtil().parseJD(keywords);
// 把查询的数据放入es
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("2m");
for (int i = 0 ; i <contents.size();i++){
bulkRequest.add(
new IndexRequest("jd_goods")
.source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
}
BulkResponse bulk = restHighLevelClient
.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
这里是我们es中最重要的一点,高亮显示,加分页,这是service的代码
// 3、高亮搜索
public List<Map<String,Object>> highlighter(String keyword,int pageNo,int pageSize) throws IOException {
if (pageNo<=1){
pageNo = 1 ;
}
// 条件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 分页
searchSourceBuilder.from();
// 精准匹配
TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
searchSourceBuilder.query(title);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// 高亮配置
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
// 多个高亮显示删除
highlightBuilder.requireFieldMatch(false);
highlightBuilder.preTags("<span style ='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
// 执行搜索
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 解析结果
ArrayList<Map<String,Object>> objects = new ArrayList<>();
for (SearchHit documentFields : searchResponse .getHits().getHits()) {
// 解析高亮字段
Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
HighlightField titlel = highlightFields.get("title");
Map<String, Object> sourceAsMap = documentFields.getSourceAsMap(); //原来的结果
// 将原来的字段换为我们高亮的字段
if (titlel!=null){
Text[] fragments = titlel.fragments();
String name ="";
for (Text fr: fragments) {
name += fr;
}
// 高亮字段替换原来的内容
sourceAsMap.put("title",name);
}
objects.add(sourceAsMap);
}
return objects;
}
以下是代码成功图片
一个很厉害的大佬讲解
原创地址 https://space.bilibili.com/95256449/channel/detail?cid=146244