ElasticSearch仿京东搜索实战
Posted 雙馬程序猿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ElasticSearch仿京东搜索实战相关的知识,希望对你有一定的参考价值。
1.项目介绍
此项目是跟随狂神ES课程入门所做的SpringBoot+ES+Vue实战项目,在视频的基础上,已实现前后端分离。功能比较简单,实现的基本的爬虫+储存+搜索+高亮
此项目涉及以下功能
- ES创建索引
- ES删除索引
- ES批量插入文档
- ES查询并高亮显示
- 最基础的JAVA爬虫(Jsoup)
- Vue基本操作
运行环境
- elasticsearch 7.6.1
- IDEA 2022.2
- Maven 3.8.6
- SpringBoot 2.7.9
前期准备
- 安装ElasticSearch、Kibana、ik分词器,注意这三个版本必须保持一致!
2.环境搭建
- 1.在es整合springboot中新建一个模块,或新建一个项目都可,这里新建一个模块
- 2.创建好后查看语言版本、javac和jdk版本
- 3.修改es版本,这里springboot自带版本是高于本机的es版本的,并不会自适应,在pom里修改一下es的版本控制
<properties>
<java.version>1.8</java.version>
<!--自定义版本和本地版本一致-->
<elaticsearch.version>7.6.1</elaticsearch.version>
</properties>
- 4.将es之前的依赖导入pom.xml里面
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.23</version>
</dependency>
- 5.将基础配置环境搭建
server.port=9090
# 关闭thymeleaf缓存
spring.thymeleaf.cache=false
- 6.将静态资源导入
这里直接去我的gitee下载
- 7.编写controller层
@Controller
public class IndexController
@GetMapping("/", "/index")
public String index()
return "index";
- 8.启动主启动类并访问 localhost:9090 测试,访问成功即可
3.爬取数据
爬取数据: (获取请求返回的页面信息,筛选出我们想要的数据就可以了! )
- 1.导入依赖
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.3</version>
</dependency>
- 2.尝试爬取一下数据,出现图片相似内容为爬取成功
@Component
public class htmlParseUtil
public static void main(String[] args) throws IOException
String url = "https://search.jd.com/Search?keyword=java";
Document document = Jsoup.parse(new URL(url), 30000);
Element element = document.getElementById("J_goodsList");
System.out.println(element.html());
- 3.将所有li列表爬取出来,然后测试
public static void main(String[] args) throws IOException
String url = "https://search.jd.com/Search?keyword=java";
Document document = Jsoup.parse(new URL(url), 30000);
Element element = document.getElementById("J_goodsList");
Elements elements = element.getElementsByTag("li");
for (Element el : elements)
//关于这种图片特别多的网站,所有的图片都是延迟加载的
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);
- 4.将代码提取成工具类,在此之前先封装一下对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Content
private String title;
private String img;
private String price;
- 5.提取工具类
@Component
public class HtmlParseUtil
public List<Content> parseJD(String keywords) throws Exception
//获取请求
String url = "https://search.jd.com/Search?keyword=" + keywords;
//解析网页。(Jsoup返回Document就是浏览器Document对象)
Document document = Jsoup.parse(new URL(url), 30000);
//所有你在js中可以使用的方法,这里都能用
Element element = document.getElementById("J_goodsList");
//获取所有的li元素
Elements elements = element.getElementsByTag("li");
ArrayList<Content> goodsList = new ArrayList<>();
//获取元素中的内容,这里el 就是每一个li标签了
for (Element el : elements)
//关于这种图片特别多的网站,所有的图片都是延迟加载的
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.setTitle(title);
content.setImg(img);
content.setPrice(price);
goodsList.add(content);
return goodsList;
- 6.测试,这里测试完后,展示出下图内容,即可删除
public static void main(String[] args) throws Exception
new HtmlParseUtil().parseJD("java").forEach(System.out::println);
- 7.当前项目结构
4.编写业务层
解析数据放入到es索引中
- 1.项目结构整理,这里将结构添加与以下图片内容相同即可
- 2.将之前es整合springboot的config给拿过来
@Configuration
public class ElasticSearchConfig
@Bean
public RestHighLevelClient restHighLevelClient()
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")
)
);
return client;
- 3.使用elasticsearch-head新建一个 jd_goods 的索引
- 4.编写业务层的
// 业务编写
@Service
public class ContentService
@Autowired
RestHighLevelClient restHighLevelClient;
//1、解析数据放入 es 索引中
public boolean parseContent(String keyword) throws Exception
List<Content> contents = new HtmlParseUtil().parseJD(keyword);
// 把查询到的数据放入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();
- 5.编写controller层
// 请求编写
@RestController
public class ContentController
@Autowired
private ContentService contentService;
@GetMapping("/parse/keyword")
public boolean parse(@PathVariable("keyword")String keyword) throws Exception
return contentService.parseContent(keyword);
- 6.启动主启动类测试
网页是没有数据的
es-head也没有数据
- 7.进行访问 localhost:9090/parse/java ,返回true则为添加成功,然后查看es-head,发现已经插入进去了
这里解析需要点时间,可能后面的内容没有加载出来,稍等一下,两分钟后刷新一下网页就可以如图所示
获取es中的数据实现搜索功能
- 1.编写service层
//2、获取这些数据实现搜索功能
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();
//分页
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
//精准匹配
TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
sourceBuilder.query(title);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//执行搜索
searchRequest.source(sourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//解析结果
ArrayList<Map<String,Object>> list = new ArrayList<>();
for (SearchHit documentFields: search.getHits().getHits())
list.add(documentFields.getSourceAsMap());
return list;
- 2.编写controller层
@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.访问 localhost:9090/search/java/1/10 进行测试,如下图表示成功
5.前端后台交互
导入axios.min.js、vue.min.js(这两个资源在这里就不发送了,去官网下载或者查看我开始说的gitee开源项目下载)
页面代码
资源放入的结构
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>狂神说Java-ES仿京东实战</title>
<link rel="stylesheet" th:href="@/css/style.css"/>
</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 @click.prevent="searchPage" type="submit" 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="item in results">
<div class="product-iWrap">
<!--商品封面-->
<div class="productImg-wrap">
<a class="productImg">
<img :src="item.img">
</a>
</div>
<!--价格-->
<p class="productPrice">
<em>item.price</em>
</p>
<!--标题-->
<p class="productTitle">
<a >item.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>
<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:
searchPage()
let keyword = this.keyword;
console.log(keyword)
axios.get("/search/"+keyword+"/1/10").then(res=>
console.log(res)
this.results = res.data;//绑定数据
)
)
</script>
</body>
</html>
6.搜索高亮
- 1.service层
//3、获取这些数据实现高亮功能
public List<Map<String,Object>> searchPageHighlightBuilder(String keyword,int pageNo,int pageSize) throws IOException
if(pageNo<=1)
pageNo = 1;
// 条件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//分页
sourceBuilder.from(pageNo);
sourceBuilder.size(pageSize);
//精准匹配
TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
sourceBuilder.query(title);
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);
//执行搜索
searchRequest.source(sourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//解析结果
ArrayList<Map<String,Object>> list = new ArrayList<>();
for (SearchHit hit: search.getHits().getHits())
//解析高亮的字段
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField title1 = highlightFields.get("title");
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//解析高亮的字段,将原来的字段换位我们高亮的字段即可
if(title1 != null)
Text[] fragments = title1.fragments();
String n_title = "";
for (Text text : fragments)
n_title += text;
sourceAsMap.put("title",n_title);//高亮字段替换掉原来的内容
list.add(sourceAsMap);
return list;
- 2.controller层替换为高亮的
@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.searchPageHighlightBuilder(keyword,pageNo,pageSize);
- 3.进行测试发现高亮的内容已经被嵌套了,只是前端并没有解析
- 4. 这里使用vue的v-html解析内容,将前端标题行修改为以下内容
<!--标题-->
<p class="productTitle">
<a v-html="item.title"></a>
</p>
- 5.再次重启idea查看结果
以上是关于ElasticSearch仿京东搜索实战的主要内容,如果未能解决你的问题,请参考以下文章