SpringBoot2.0+ElasticSearch实现搜索高亮
实现效果
前提准备条件
springboot2.0以上版本
ElasticSearch本地安装
elasticsearch-head-master本地安装
安装完上述条件之后启动es及其head之后,访问出现
之后就可以进行SpringBoot项目整合了
- 创建SpringBoot项目
创建之后项目结构如下
开始准备
- pom.xml进行导包操作
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
2.引入前端相关页面(相关页面在博客最后会给gitee相关链接)
3.application.yml文件新增相关端口设置及thymeleaf缓存设置
server.port=8080
spring.thymeleaf.cache=false
4.新建ElasticSearchController测试类
@Controller
public class ElasticSearchController {
@GetMapping("/index")
public String get() {
return "index";
}
}
5.访问测试
6.新建Content pojo类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Content {
private String price;
private String title;
private String img;
}
7.新建ParseUtil工具类获取一下jd相关的商品数据信息
@Component
public class ParseUtil {
public static void main(String[] args) throws Exception {
new ParseUtil().getJD("java").forEach(System.out::println);
}
public List<Content> getJD(String args) throws Exception {
// https://search.jd.com/Search?keyword=java 看搜索实现效果图片(第一张)
String url = "https://search.jd.com/Search?keyword=" + args;
// 解析网页 xml的包引入之后刷新一下
Document document = Jsoup.parse(new URL(url), 30000);
Element element = document.getElementById("J_goodsList");
Elements elements = element.getElementsByTag("li");
ArrayList<Content> objects = new ArrayList<>();
for (Element element1 : elements) {
String img = element1.getElementsByTag("img").eq(0).attr("src");
String price = element1.getElementsByClass("p-price").eq(0).text();
String title = element1.getElementsByClass("p-name").eq(0).text();
// pojo类
Content content = new Content();
content.setImg(img);
content.setPrice(price);
content.setTitle(title);
objects.add(content);
}
return objects;
}
}
8.新建ContentService类添加相关的业务代码
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
/**
* 爬取页面
* @param keyword
* @return
* @throws Exception
*/
public Boolean parse(String keyword) throws Exception {
BulkRequest bulkRequest = new BulkRequest();
// 超时时间
bulkRequest.timeout("2m");
List<Content> jd = new ParseUtil().getJD(keyword);
for (int i = 0; i < jd.size(); i++) {
bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(jd.get(i)), XContentType.JSON));
}
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
9.添加ContentController类
@RestController
public class ContentController {
@Autowired
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws Exception {
return contentService.parse(keyword);
}
}
10.新建ElasticSearchClientConfig配置类
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
// 发现本地的服务 多个可配置集群
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
}
}
11.访问parse方法向elasticsearch添加数据
可以把java替换成vue或者其他的名字,多搜索资源保存到本地
12.测试分页返回搜索service和controller分别添加对应方法
ContentService
/**
* 分页搜索高亮
* @param keyword
* @param pageNo
* @param pageSize
* @return
* @throws IOException
*/
public List<Map<String, Object>> getPageHighlightBuilder(String keyword, int pageNo, int pageSize) throws IOException {
if (pageNo <= 1) {
pageNo = 1;
}
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//分页
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
// 搜索高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
// 多个高亮的显示
highlightBuilder.requireFieldMatch(true);
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
sourceBuilder.highlighter(highlightBuilder);
TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
sourceBuilder.query(termQuery);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
List<Map<String, Object>> goodsListMap = new ArrayList<>();
if (search != null) {
for (SearchHit hit : search.getHits().getHits()) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
// 高亮字段替换 title = java360 替换后 title = <span style='color:red'>java</span>360
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField title = highlightFields.get("title");
if (title != null) {
Text[] fragments = title.fragments();
String n_title = "";
for (Text fragment : fragments) {
n_title += fragment;
}
sourceAsMap.put("title", n_title);
}
goodsListMap.add(sourceAsMap);
}
}
return goodsListMap;
}
ContentController
@GetMapping("/page/{keyword}/{pageNo}/{pageSize}")
public List<Map<String, Object>> parsePage(@PathVariable("keyword") String keyword,
@PathVariable("pageNo") int pageNo,
@PathVariable("pageSize") int pageSize) throws Exception {
return contentService.getPageHighlightBuilder(keyword, pageNo, pageSize);
}
测试访问
13.结合index.html实现
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>ES仿京东实战</title>
<link rel="stylesheet" th:href="@{/css/style.css}"/>
</head>
<body class="pg">
<div id="app" class="page">
<div id="mallPage" class=" mallist tmall- page-not-market ">
<!-- 头部搜索 -->
<div id="header" class=" header-list-app">
<div class="headerLayout">
<div class="headerCon ">
<!-- Logo-->
<h1 id="mallLogo">
<img th:src="@{/images/jdlogo.png}" alt="">
</h1>
<div class="header-extra">
<!--搜索-->
<div id="mallSearch" class="mall-search">
<form name="searchTop" class="mallSearch-form clearfix">
<fieldset>
<legend>天猫搜索</legend>
<div class="mallSearch-input clearfix">
<div class="s-combobox" id="s-combobox-685">
<div class="s-combobox-input-wrap">
<input v-model="keyword" type="text" autocomplete="off" value="dd"
id="mq"
class="s-combobox-input" aria-haspopup="true">
</div>
</div>
<button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
</div>
</fieldset>
</form>
<ul class="relKeyTop">
<li><a>狂神说Java</a></li>
<li><a>狂神说前端</a></li>
<li><a>狂神说Linux</a></li>
<li><a>狂神说大数据</a></li>
<li><a>狂神聊理财</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- 商品详情页面 -->
<div id="content">
<div class="main">
<!-- 品牌分类 -->
<form class="navAttrsForm">
<div class="attrs j_NavAttrs" style="display:block">
<div class="brandAttr j_nav_brand">
<div class="j_Brand attr">
<div class="attrKey">
品牌
</div>
<div class="attrValues">
<ul class="av-collapse row-2">
<li><a href="#"> 狂神说 </a></li>
<li><a href="#"> Java </a></li>
</ul>
</div>
</div>
</div>
</div>
</form>
<!-- 排序规则 -->
<div class="filter clearfix">
<a class="fSort fSort-cur">综合<i class="f-ico-arrow-d"></i></a>
<a class="fSort">人气<i class="f-ico-arrow-d"></i></a>
<a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
<a class="fSort">销量<i class="f-ico-arrow-d"></i></a>
<a class="fSort">价格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
</div>
<!-- 商品详情 -->
<div class="view grid-nosku">
<div class="product" v-for="result in results">
<div class="product-iWrap">
<!--商品封面-->
<div class="productImg-wrap">
<a class="productImg">
<img :src="result.img">
</a>
</div>
<!--价格-->
<p class="productPrice">
<em>{{result.price}}</em>
</p>
<!--标题-->
<p class="productTitle">
<a v-html="result.title"> </a>
</p>
<!-- 店铺名 -->
<div class="productShop">
<span>店铺: 京东自营 </span>
</div>
<!-- 成交信息 -->
<p class="productStatus">
<span>月成交<em>999笔</em></span>
<span>评价 <a>3</a></span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.common.dev.js"></script>-->
<script th:src="@{/js/vue.min.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>
<script>
new Vue({
el: '#app',
data: {
keyword: '', // 搜索关键字
results: [] // 搜索的结果
},
methods: {
searchKey() {
let keyword = this.keyword;
axios.get('page/' + keyword + '/1/10').then(
res => {
console.log(res)
this.results = res.data;
}
)
}
}
})
</script>
</body>
</html>
新增MyWebMvcConfigurerAdapter类解决静态资源访问问题
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
/**
* 配置静态访问资源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}