1. 项目准备
1.1 前端资源
一个html页面+css+js;从京东商城爬取简单页面
1.2 ElasticSearch 7.6.2 环境安装
我的前两篇博客可以参考一下:https://www.cnblogs.com/qi-chao/p/15179254.html
1.3 创建Springboot工程
1、导入依赖(注意ElasticSearch版本)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2、配置yml
spring:
thymeleaf:
cache: false
server:
port: 9090
3、引入静态资源
4、写个 IndexController
测试下项目正常运行
@Controller
public class IndexController {
@GetMapping({"/", "/index"})
public String index() {
return "index";
}
}
输入:localhost:9090
2. 爬取京东数据到ES中
2.1 爬取数据
2.1.1 分析网页,得到相应标签
2.1.2 设计Content实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Content implements Serializable {
private String title;
private String img;
private String price;
}
2.1.3 写个工具类 HtmlParseUtil
测试一下
@Component
public class HtmlParseUtil {
public static void main(String[] args) throws IOException {
new HtmlParseUtil().parseJD("java").forEach(System.out::println);
}
public ArrayList<Content> parseJD(String keywords) throws IOException {
// 获取请求,前提需要联网,ajax不能获取到!
String url = "https://search.jd.com/Search?keyword=" + keywords + "&enc=utf-8";
// 解析网页.(Jsoup返回的Document就是页面对象)
Document document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12").timeout(30000).get();
// 所有你在js中可以使用的方法
Element element = document.getElementById("J_goodsList");
// 获取所有的li元素
Elements elements = element.getElementsByTag("li");
// 获取元素中的内容,el代表每一个li标签
ArrayList<Content> goodsList = new ArrayList<>();
for (Element el : elements) {
// 关于这种图片特别多的网站,都是延迟加载的
String image = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
String price = el.getElementsByClass("p-price").eq(0).text();
String title = el.getElementsByClass("p-name").eq(0).text();
Content content = new Content();
content.setTitle(title);
content.setImg(image);
content.setPrice(price);
goodsList.add(content);
}
return goodsList;
}
}
可以发现,我们成功拿到了网页内容
2.2 数据入库
2.2.1 ContentService
@Service
public class ContentService {
@Autowired
private RestHighLevelClient restHighLevelClient;
// 1.解析数据 放入ES索引库
public Boolean parseContent(String keywords) throws IOException {
List<Content> contents = new HtmlParseUtil().parseJD(keywords);
// 2.查询的数据批量插入ES中
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("3m");
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();
}
}
2.2.2 ContentController
@RestController
public class ContentController {
@Autowired
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws IOException {
return contentService.parseContent(keyword);
}
}
2.2.3 创建索引库 jd_goods,测试执行搜索 java 入库
1、输入:localhost:9090/parse/java
2、查看ES数据库,发现成功入库
3. 搜索功能【关键词非高亮】
3.1 ContentController
// 不带高亮
@GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
public List<Map<String,Object>> search(@PathVariable("keyword") String keyword,
@PathVariable("pageNo") int pageNo,
@PathVariable("pageSize") int pageSize) throws IOException {
return contentService.searchPage(keyword, pageNo, pageSize);
}
3.2 ContentService实现搜索功能
// 2.实现搜索功能
public List<Map<String,Object>> searchPage(String keyword,int pageNo, int pageSize) throws IOException {
if (pageNo<=1){
pageNo=1;
}
// 条件搜索
SearchRequest jd_goods = new SearchRequest("jd_goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 分页
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
// 精准查询
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title",keyword);
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// 执行
jd_goods.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
ArrayList<Map<String,Object>> list = new ArrayList<>();
for (SearchHit documentFields : response.getHits().getHits()) {
list.add(documentFields.getSourceAsMap());
}
return list;
}
3.4 测试,从数据库拿数据
输入:localhost:9090/search/java/1/10
3.5 前端 Vue
<!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}"/>
<script th:src="@{/js/jquery.min.js}"></script>
</head>
<body class="pg">
<div class="page" id="app">
<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>python</a></li>
<li><a>linux</a></li>
<li><a>springboot</a></li>
<li><a>elasticsearch</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="#"> 字节跳动 </a></li>
<li><a href="#"> 腾讯 </a></li>
<li><a href="#"> 网易 </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><b>¥</b>{{result.price}}</em>
</p>
<!--标题-->
<p class="productTitle">
<a> {{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>
<!--前端使用vue完成前后端分离-->
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/vue.min.js}"></script>
<script>
new Vue({
el: '#app',
data: {
keyword:'', //搜索关键字
results:[] //搜索结果
},
methods: {
searchKey(){
let keyword = this.keyword;
console.log(keyword);
//对接后端的接口
axios.get('/search/'+keyword+"/1/10").then(response=>{
console.log(response);
this.results = response.data; //绑定数据
})
}
}
})
</script>
</body>
</html>
测试搜索功能,输入java
4. 关键词高亮
4.1 ContentService 实现搜索高亮功能
// 3.实现搜索高亮功能
public List<Map<String,Object>> searchHighLightPage(String keyword,int pageNo, int pageSize) throws IOException {
if (pageNo <= 1) {
pageNo = 1;
}
// 条件搜索
SearchRequest jd_goods = new SearchRequest("jd_goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 分页
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
// 精准查询
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title",keyword);
sourceBuilder.query(termQueryBuilder);
sourceBuilder.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>");
sourceBuilder.highlighter(highlightBuilder);
// 执行
jd_goods.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
ArrayList<Map<String,Object>> list = new ArrayList<>();
for (SearchHit documentFields : response.getHits().getHits()) {
// 解析高亮字段
Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
HighlightField title = highlightFields.get("title");
Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
// 原来的字段替换为高亮字段
if (title!=null){
Text[] fragments = title.fragments();
String n_title = "";
for (Text text : fragments){
n_title += text;
}
sourceAsMap.put("title",n_title);
}
list.add(sourceAsMap);
}
return list;
}
4.2 修改ContentController
@GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
public List<Map<String,Object>> search(@PathVariable("keyword") String keyword,
@PathVariable("pageNo") int pageNo,
@PathVariable("pageSize") int pageSize) throws IOException {
return contentService.searchHighLightPage(keyword, pageNo, pageSize);
}
4.3 重启测试,发现标题变成html
4.4 在 index.html
中解析title
<!--标题-->
<p class="productTitle">
<a v-html="result.title"> </a>
</p>