一、创建项目
第一步,创建项目,填写工程信息
添加依赖
搜索页面链接代码
pan.baidu.com/s/1vWZCx1aOWgCcOvhqV42Hcw
rlwp
二、给出代码
2.1完整pom.xml代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.es.mo</groupId>
<artifactId>es-jd</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es-jd</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2配置application.properties文件
server.port=9090
#关闭thymeleaf 缓存
spring.thymeleaf.cache=false
注意: 使用thymeleaf 默认访问路径为templates 并且默认后缀为html
2.3添加静态资源文件
2.4创建首页显示控制类
/**
* @program: es7-mo
* @description: 创建首页显示控制类
* @author: WEN
* @create: 2020-07-25
**/
@Controller
public class IndexController {
@GetMapping({"/","index"})
public String index(){
return "index";
}
}
2.5启动并且测试
访问
2.6使用爬虫 获取数据
数据问题?数据库获取,消息队列中获取,都可以成为数据源或者爬虫
2.7使用jsoup包
<!--jsoup解析网页 也可以使用tika-->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
目录结构
测试 jsop 爬取 jd显示数据
HtmlHarseUtil代码
public class HtmlHarseUtil {
public static void main(String[] args) throws Exception {
// 获取请求 https://search.jd.com/Search?keyword=java
//ajax 请求不能获取
String url = "https://search.jd.com/Search?keyword=java";
//解析网页 30秒 没返回 报错 (jsoup 返回document就是页面document对象
Document document = Jsoup.parse(new URL(url), 30000);
//所有js中能做的操作 document 对象都能使用
Element element = document.getElementById("J_goodsList");
// System.out.println(element.html());
//获取所有的li 元素
Elements elements = element.getElementsByTag("li");
//获取元素中所有li标签
for (Element el : elements){
// 关于这种图片特别多的 网站 所有图片都是延迟加载
// source-data-lazy-img
// System.out.println(el.html());
//获取图片标签 获取当前li标签 第一个 图片 src 属性
String img= el.getElementsByTag("img").eq(0).attr("src");
//String img= el.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
//1. 通过class 属性为 p-price的元素的 第一个元素的文本内容
String price = el.getElementsByClass("p-price").eq(0).text();
String pname = el.getElementsByClass("p-name").eq(0).text();
System.out.println("img===>"+img);
System.out.println("price===>"+price);
System.out.println("pname===>"+pname);
}
}
}
运行测试
创建实体类Content存储数据
/**
* @program: es7-mo
* @description: 内容实体类
* @author: WEN
* @create: 2020-07-25
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Content {
private String title;
private String img;
private String price;
//可以自己添加数据
}
再创建一个工具类UtilOfKeyWord 并测试
/**
* @program: es7-mo
* @description: 实体类封装的工具类
* @author: WEN
* @create: 2020-07-25
**/
public class UtilOfKeyWord {
public static void main(String[] args) throws Exception{
// parseJD("java").forEach(System.out::println);
parseJD("开发").forEach(content -> System.out.println(content));
}
public static List<Content> parseJD(String keyword) throws Exception {
String url = "https://search.jd.com/Search?keyword="+keyword;
Document document = Jsoup.parse(new URL(url), 30000);
Element element = document.getElementById("J_goodsList");
Elements elements = element.getElementsByTag("li");
ArrayList<Content> list = new ArrayList<>();
for (Element el : elements){
String img= el.getElementsByTag("img").eq(0).attr("src");
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);
content.setPrice(price);
content.setTitle(title);
list.add(content);
}
return list;
}
}
2.8 添加 配置文件 config/ElasticSearchConfig.java
/**
* @program: es7-mo
* @description:
* @author: WEN
* @create: 2020-07-25
**/
@Configuration //创建启动配置 启动时 创建RestHighLevelClient
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
2.9编写业务类
将jd 查询数据存储es中
/**
* @program: es7-mo
* @description: 业务层
* @author: WEN
* @create: 2020-07-25
**/
@Service
public class ContentService {
@Autowired
private RestHighLevelClient restHighLevelClient;
public Boolean parseContent(String keywords) throws Exception{
List<Content> contents = UtilOfKeyWord.parseJD(keywords);
//将查询到的数据放入es中
BulkRequest bulkRequest = new BulkRequest();
//超时时间2分钟
bulkRequest.timeout("2m");
for (Content ct :contents){
bulkRequest.add(
new IndexRequest("jd_goods")
.source(JSON.toJSONString(ct), XContentType.JSON));
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
}
2.10 编写ContentController
/**
* @program: es7-mo
* @description: 内容控制层
* @author: WEN
* @create: 2020-07-25
**/
@RestController
public class ContentController {
@Autowired
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws Exception{
return contentService.parseContent(keyword);
}
}
将京东数据存储es中
访问请求
http://localhost:9090/parse/java
es 中显示内容
三、实现搜索功能
3.1 编写搜索业务方法
ContentService层代码
/**
* @program: es7-mo
* @description: 业务层
* @author: WEN
* @create: 2020-07-25
**/
@Service
public class ContentService {
@Autowired
private RestHighLevelClient restHighLevelClient;
public Boolean parseContent(String keywords) throws Exception{
List<Content> contents = UtilOfKeyWord.parseJD(keywords);
//将查询到的数据放入es中
BulkRequest bulkRequest = new BulkRequest();
//超时时间2分钟
bulkRequest.timeout("2m");
for (Content ct :contents){
bulkRequest.add(
new IndexRequest("jd_goods")
.source(JSON.toJSONString(ct), XContentType.JSON));
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws Exception {
if(pageNo <=1){
pageNo =1;
}
//条件搜索
SearchRequest searchRequest = 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;font-weight: bold'>"); //设置标签头
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 documentFields: search.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;
}
}
ContentController层代码
/**
* @program: es7-mo
* @description: 内容控制层
* @author: WEN
* @create: 2020-07-25
**/
@RestController
public class ContentController {
@Autowired
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws Exception{
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 Exception{
if(pageNo==0){
pageNo=1;
}
List<Map<String, Object>> list = contentService.searchPage(keyword, pageNo, pageSize);
System.out.println("输出:"+list);
return list;
}
}
index.html代码
<!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 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>店铺: 小莫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/axios.min.js}"></script>
<script th:src="@{/js/vue.min.js}"></script>
<script>
new Vue({
el:"#app",
data :{
keyword:"",//搜索关键字
results:[] //搜索结果
},
methods: {
searchKey() {
var keyword = this.keyword;
console.log(keyword);
//对接后端的接口
axios.get('search/'+keyword+"/1/10").then(response=>{
console.log(response)
this.results=response.data;
})
}
}
})
</script>
</body>
</html>
页面展示效果
四、完结
致谢
参考链接:
https://space.bilibili.com/95256449?spm_id_from=333.788.b_765f7570696e666f.1