ElasticSearch_仿京东搜索
仿京东搜索
本博客内容根据狂神说整理
https://www.bilibili.com/video/BV17a4y1x7zq
1. 爬虫
首先明确数据从哪里来
- 数据库中获取
- 消息队列中获取
- 爬虫
- ......
爬取数据 : 获取请求返回的页面信息, 筛选出屋面想要的信息就可以了!
导入依赖 JSoup, 解析网页 ==> 爬电影, 音乐, 用tika
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
1. 测试使用爬虫
package com.wang.wangesjd.utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URL;
public class HtmlParseUtil {
public static void main(String[] args) throws IOException {
//获取请求 https://search.jd.com/Search?keyword=java
//前提: 需要联网, 而且不能获取到AJAX!
String url = "https://search.jd.com/Search?keyword=java";
//设置超时时间 30S
int timeOut = 30000;
//解析网页 ==> Document就是浏览器的Document对象
Document document = Jsoup.parse(new URL(url), timeOut);
//所有你在JS中可以使用的方法, 这里都能用!
Element element = document.getElementById("J_goodsList");
// System.out.println(element.html());
//获取所有的li元素
Elements elements = element.getElementsByTag("li");
//获取元素中的内容, 这里的el就是每一个li标签了
for (Element el : elements) {
//关于这种图片特别多的网站, 所有的图片都是延迟加载的!
//JD 放在了这个class data-lazy-img
String img = 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();
System.out.println("===================================================");
System.out.println(img);
System.out.println(price);
System.out.println(title);
}
}
}
- 注意
- JD 貌似图片使用了反爬虫技术, 要获取的属性名和我们在前端调试时看到的不一样...
2. 提取工具类
package com.wang.wangesjd.utils;
import com.wang.wangesjd.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class HtmlParseUtil {
public static void main(String[] args) throws IOException {
//URL会将符号转义!
// HtmlParseUtil.parseJD("C%2B%2B").forEach(System.out::println);
//查询中文需要URL转码
// HtmlParseUtil.parseJD("心理学").forEach(System.out::println);
HtmlParseUtil.parseJD("C++").forEach(System.out::println);
}
public static List<Content> parseJD(String keywords) throws IOException {
//URL会对符号和汉字转码
//要先转码再拼接, 否则URL无法解析 (因为会将url中的符号也一起转码, 无法识别)
String urlKeywords = URLEncoder.encode(keywords, "UTF-8");
//获取请求 https://search.jd.com/Search?keyword=java
//前提: 需要联网, 而且不能获取到AJAX!
String url ="https://search.jd.com/Search?keyword=" + urlKeywords + "&enc=utf-8";
//设置超时时间 30S
int timeOut = 30000;
//解析网页 ==> Document就是浏览器的Document对象
Document document = Jsoup.parse(new URL(url), timeOut);
//所有你在JS中可以使用的方法, 这里都能用!
Element element = document.getElementById("J_goodsList");
//获取所有的li元素
Elements elements = element.getElementsByTag("li");
List<Content> goodsList = new ArrayList<>();
//获取元素中的内容, 这里的el就是每一个li标签了
for (Element el : elements) {
//关于这种图片特别多的网站, 所有的图片都是延迟加载的!
//JD 放在了这个class data-lazy-img
String img = 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.setImg(img)
.setPrice(price)
.setTitle(title);
goodsList.add(content);
}
return goodsList;
}
}
- 注意
- URL解析时会转义符号和中文, 因此如果我们想传递中文或者符号的关键字, 需要先转义
- 不能将拼接后的url转义, 这样会导致URL中正常的符号也被转义, 导致无法识别, 正确的做法是先将被拼接的转义, 再拼接即可
3. 编写实体类和业务层
1. 实体类
package com.wang.wangesjd.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Content {
private String img;
private String price;
private String title;
}
2. 业务层
这里有个小坑 ==> SpringBoot接管类, 如果是静态方法, 使用自动装载无法使用静态方法
package com.wang.wangesjd.service;
import com.alibaba.fastjson.JSON;
import com.wang.wangesjd.pojo.Content;
import com.wang.wangesjd.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class ContentService {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient rest;
@Autowired
private HtmlParseUtil htmlParseUtil;
//解析数据, 放入ES索引中
public Boolean parseContent(String keywords) throws IOException {
List<Content> contents = htmlParseUtil.parseJD(keywords);
//把查询的数据放入ES中
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout(TimeValue.timeValueMinutes(2L));
for (int i = 0; i < contents.size(); i++) {
bulkRequest.add(new IndexRequest("jd_goods")
.source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
}
BulkResponse bulk = rest.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
//获取这些数据(从ES索引中), 实现搜索功能
// public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
// if (pageNo <= 1) {
// pageNo = 1;
// }
// //条件搜索
// SearchRequest searchRequest = new SearchRequest("jd_goods");
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// //精准匹配
// MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
// sourceBuilder.query(matchQueryBuilder)
// .timeout(TimeValue.timeValueMinutes(1L));
// //分页
// sourceBuilder.from(pageNo)
// .size(pageSize);
// //执行搜索
// searchRequest.source(sourceBuilder);
// SearchResponse searchResponse = rest.search(searchRequest, RequestOptions.DEFAULT);
// //解析结果
// List<Map<String, Object>> list = new ArrayList<>();
// for (SearchHit documentFields : searchResponse.getHits()) {
// list.add(documentFields.getSourceAsMap());
// }
// return list;
// }
//实现搜索高亮
public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
if (pageNo <= 1) {
pageNo = 1;
}
//条件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//精准匹配
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
sourceBuilder.query(matchQueryBuilder)
.timeout(TimeValue.timeValueMinutes(1L));
//高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
//定义要高亮的标签和样式
highlightBuilder.field("title")
.preTags("<span style='color:red'>")
.postTags("</span>")
.requireFieldMatch(false); //是否需要高亮多个字段
sourceBuilder.highlighter(highlightBuilder);
//分页
sourceBuilder.from(pageNo)
.size(pageSize);
//执行搜索
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = rest.search(searchRequest, RequestOptions.DEFAULT);
//解析结果
List<Map<String, Object>> list = new ArrayList<>();
for (SearchHit documentFields : searchResponse.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 highlightTitle = "";
for (Text text : fragments) {
highlightTitle += text;
}
//将高亮字段替换没有高亮的字段
sourceAsMap.put("title", highlightTitle);
}
list.add(sourceAsMap);
}
return list;
}
}
4. 页面跳转
package com.wang.wangesjd.controller;
import com.wang.wangesjd.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RestController
public class ContentController {
@Autowired
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable String keyword) throws IOException {
return contentService.parseContent(keyword);
}
@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);
}
}
使用RestFul风格
5. 前端
<!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 src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.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>狂神说前端</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><b>¥</b>{{result.price}}</em>
</p>
<!--标题, 我们传递的是一个html-->
<p class="productTitle">
<a v-html="result.title"></a>
</p>
<!-- 店铺名 -->
<div class="productShop">
<span>店铺: 狂神说Java </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>
new Vue({
el: '#app',
data: {
keyword: '', //搜索的关键字
results: [] //搜索的结果
},
methods: {
searchKey() {
let keyword = this.keyword;
console.log(keyword);
//对接后端的接口
axios.get('search/' + keyword + "/0/10").then(response => {
console.log(response.data);
this.results = response.data; //绑定数据
})
}
}
})
</script>
</body>
</html>
- 注意
- 由于后端高亮传回来的是一个html, 我们需要解析, 不能单纯的双向绑定, 因此用 v-html