文章目录

  • 1. 版本兼容
  • 2. 导入依赖
  • 3. 配置
  • 4. 主页面
  • 5. 控制层
  • 6. 逻辑处理层
  • 7. pojo
  • 8. 工具类
  • 9. 常量类
  • 10. 前端页面
  • 项目开源地址
1. 版本兼容
框架/组件 版本
SpringBoot 2.6.1
elasticsearch 7.1.5
2. 导入依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.1</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><!--解析网页--><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.14.3</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.78</version></dependency><!--springboot <=2.2.5 需要指定es版本默认引入es版本6.x--><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-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><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></dependency></dependencies>
3. 配置
server.port=9090
spring.thymeleaf.cache=false

ElasticsearchClientConfig

package com.gblfy.es7jdvue.config;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** es7 高级API客户端** @author gblfy* @date 2021-12-01*/
@Configuration
public class ElasticsearchClientConfig {@Beanpublic RestHighLevelClient restHighLevelClient() {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));return client;}
}
4. 主页面
package com.gblfy.es7jdvue.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;/*** 主页面** @author gblfy* @date 2021-12-02*/
@Controller
public class IndexController {@GetMapping({"/index"})public String index() {return "index";}
}
5. 控制层
package com.gblfy.es7jdvue.controller;import com.gblfy.es7jdvue.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;/*** 搜索业务入口** @author gblfy* @date 2021-12-02*/
@RestController
public class ContentController {@Autowiredprivate ContentService contentService;/*** 将数据存入es** @param keyword* @return* @throws IOException*/@GetMapping("/parse/{keyword}")public Boolean parse(@PathVariable("keyword") String keyword) throws IOException {return contentService.parseContent(keyword);}/*** 获取es中的数据,实现基本搜索高亮功能** @param keyword* @param pageNo* @param pageSize* @return* @throws IOException*/@GetMapping("/search/{keyword}/{pageNo}/{pageSize}")public List<Map<String, Object>> searchPage(@PathVariable("keyword") String keyword,@PathVariable("pageNo") int pageNo,@PathVariable("pageSize") int pageSize) throws IOException {return contentService.searchPageHighlight(keyword, pageNo, pageSize);}}
6. 逻辑处理层
package com.gblfy.es7jdvue.service;import com.alibaba.fastjson.JSON;
import com.gblfy.es7jdvue.consts.ESConst;
import com.gblfy.es7jdvue.pojo.Content;
import com.gblfy.es7jdvue.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.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
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.stereotype.Service;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;/*** 搜索逻辑处理层** @author gblfy* @date 2021-12-02*/
@Service
public class ContentService {@Autowiredprivate RestHighLevelClient restHighLevelClient;//1.解析数据放入es索引中public Boolean parseContent(String keyword) throws IOException {List<Content> contentList = new HtmlParseUtil().parseJD(keyword);// 把查询道德数据放入esBulkRequest bulkRequest = new BulkRequest();bulkRequest.timeout(ESConst.BULK_REQUEST_TIMEOUT);for (int i = 0; i < contentList.size(); i++) {bulkRequest.add(new IndexRequest(ESConst.JD_SEARCH_INDEX).source(JSON.toJSONString(contentList.get(i)), XContentType.JSON));}BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);return !bulk.hasFailures();}//    2. 获取es中的数据,实现基本搜索功能public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {if (pageNo <= 1) {pageNo = 1;}//    条件搜索SearchRequest searchRequest = new SearchRequest(ESConst.JD_SEARCH_INDEX);SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//    分页searchSourceBuilder.from(pageNo);searchSourceBuilder.size(pageSize);//    精准匹配TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(ESConst.SEARCH_CONDITION_FIELD, keyword);searchSourceBuilder.query(termQueryBuilder);searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));//    执行搜索searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//    解析结果ArrayList<Map<String, Object>> list = new ArrayList<>();for (SearchHit documentFields : searchResponse.getHits().getHits()) {list.add(documentFields.getSourceAsMap());}return list;}//    2. 获取es中的数据,实现基本搜索高亮功能public List<Map<String, Object>> searchPageHighlight(String keyword, int pageNo, int pageSize) throws IOException {if (pageNo <= 1) {pageNo = 1;}//    条件搜索SearchRequest searchRequest = new SearchRequest(ESConst.JD_SEARCH_INDEX);SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//    分页searchSourceBuilder.from(pageNo);searchSourceBuilder.size(pageSize);//    精准匹配TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(ESConst.SEARCH_CONDITION_FIELD, keyword);searchSourceBuilder.query(termQueryBuilder);searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));//构建高亮HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.field(ESConst.HIGHLIGHT_TITLE);highlightBuilder.requireFieldMatch(false);//多个高亮 显示highlightBuilder.preTags(ESConst.HIGHLIGHT_PRE_TAGS);highlightBuilder.postTags(ESConst.HIGHLIGHT_POST_TAGS);searchSourceBuilder.highlighter(highlightBuilder);//    执行搜索searchRequest.source(searchSourceBuilder);SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//    解析结果ArrayList<Map<String, Object>> list = new ArrayList<>();for (SearchHit hit : searchResponse.getHits().getHits()) {//  解析高亮的字段,将原来的字段置换为我们高亮的字段即可!Map<String, HighlightField> highlightFields = hit.getHighlightFields();HighlightField title = highlightFields.get(ESConst.HIGHLIGHT_TITLE);//    获取原来的结果Map<String, Object> sourceAsMap = hit.getSourceAsMap();if (title != null) {Text[] fragments = title.fragments();String newTitle = "";for (Text text : fragments) {newTitle += text;}//高亮字段替换掉原来的内容即可sourceAsMap.put(ESConst.SEARCH_CONDITION_FIELD, newTitle);}// 将结果放入list容器返回list.add(sourceAsMap);}return list;}}
7. pojo
package com.gblfy.es7jdvue.pojo;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Content {private String title;private String img;private String price;
}
8. 工具类
package com.gblfy.es7jdvue.pojo;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Content {private String title;private String img;private String price;
}
9. 常量类
package com.gblfy.es7jdvue.consts;/*** 搜索常量抽取** @author gblfy* @date 2021-12-02*/
public class ESConst {//拉取数据url前缀public static final String PULL_DATA_BASEURL = "https://search.jd.com/Search?keyword=";//拉取商品数据标签public static final String PULL_GOOD_DATA_TAG ="J_goodsList";//商品数据标签中元素标签public static final String PULL_GOOD_DATA_CHILD_TAG ="li";//京东搜索数据索引public static final String JD_SEARCH_INDEX = "jd_goods";//高亮标题public static final String HIGHLIGHT_TITLE = "title";//高亮标签前缀public static final String HIGHLIGHT_PRE_TAGS = "<span style='color:red'>";//高亮标签后缀public static final String HIGHLIGHT_POST_TAGS = "</span>";//搜索挑条件字段public static final String SEARCH_CONDITION_FIELD = "title";public static final String BULK_REQUEST_TIMEOUT = "2m";}
10. 前端页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><head><meta charset="utf-8"/><title>gblfyJava-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="searchKey" 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="#"> gblfy </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><b>¥</b>{{item.price}}</em></p><!--标题--><p class="productTitle"><a v-html="item.title"> </a></p><!-- 店铺名 --><div class="productShop"><span>店铺: gblfy 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 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/20").then(res => {console.log(res);this.results = res.data;//绑定数据})}}})
</script></body>
</html>
项目开源地址

https://gitee.com/gblfy/es7-jd-vue

SpringBoot2.6.1 elasticsearch7.1.5 Vue相关推荐

  1. SpringBoot2.0.3 + SpringSecurity5.0.6 + vue 前后端分离认证授权

    新项目引入安全控制 项目中新近添加了Spring Security安全组件,前期没怎么用过,加之新版本少有参考,踩坑四天,终完成初步解决方案.其实很简单,Spring Security5相比之前版本少 ...

  2. SpringBoot2.2.2+Elasticsearch7.6.2实现中文、拼音、拼音首字母智能提示功能

    一.Elasticsearch介绍 1.1 Elasticsearch是什么 Elasticsearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTfu ...

  3. Elasticsearch7.1之cerebro使用(一)

    阅读大约4分钟,文末搜一套从零到实战源码. Elasticsearch7.1  REST操作. 本博客近期教程笔记都基于elasticsearch7编写 创建空索引(put方式) 查看索引信息(dem ...

  4. Java标准简历制作

    xxx 性别:男 年龄:xx 工作经验:三年 电话:xxxxxx 现居住地:南京市 邮箱:xxxxxx 自我介绍:我叫xxx,来自河南,从业有xx年之前在xx家公司,做过的项目xxx,最近在研究的技术 ...

  5. PUSHmall 推贴订货商城系统 — — B2B/B2C批发零售采销模式,商贸流通企业最佳电商解决方案

    PUSHmall推贴 订货商城系统:B2B/B2C兼营商城系统 基于当前流行技术组合的前后端分离批零订货商城系统: SpringBoot2+SpringBoot Jpa+SpringSecurity+ ...

  6. 电商数字化解决方案趋势——订货商城系统+进销存财务系统+CRM客户管理系统

    PUSHmall 推贴数字化电商解决方案设计: 订货商城(线下线上交易)+进销存财务(管理支撑层面)+CRM客户管理(业务拓客推广) 所谓的数字化电商解决方案的设计不是一个功能模块的表现,而是重视渠道 ...

  7. 基于SpringBoot+Mybatis开发的前后端ERP系统Saas平台

    源码介绍 基于SpringBoot+Mybatis开发的前后端ERP系统Saas平台 ,专注于中小微企业的ERP软件.进销存系统,是一套基于SpringBoot2.2.0, Mybatis, JWT, ...

  8. 介绍Tduck问卷系统技术栈

    Pro技术栈 项目基于Springboot2+MybatisPlus+Mysql5.7+Redis+ElasticSearch+Vue+ElementUI 技术栈 后台模块 项目 说明 tduck-a ...

  9. 【第八篇】商城系统-库存管理

    库存管理 1. 仓库列表维护 1.1 注册中心配置 首先我们需要把库存服务注册到注册中心中. 然后在nacos中发现注册的服务 1.2 网关路由配置 客户端首先访问的都是网关服务,所以需要配置对应的路 ...

最新文章

  1. 使用early stopping解决神经网络过拟合问题
  2. 学会放下包袱,热爱单例
  3. android相对布局底部对齐,Android,在edittext中输入时防止相对布局底部对齐的按钮向上移动...
  4. leetcode 839 Similar String Groups
  5. 如何给textbox中的文本设置垂直对齐,以及右对齐
  6. struts2文件上传类型的过滤
  7. 一些牛人博客,值得收藏和学习
  8. 惠普179fnw打印机使用说明_|惠普HP Color Laser MFP 179fnw一体机驱动下载v1.10官方版 - 欧普软件下载...
  9. 计算机类专业分类及优缺点,计算机专业优势介绍及学科分类
  10. 新手不要再被误导!这是一篇最新的Xposed模块编写教程
  11. [08S01] dategrip 链接 linux mysql遇到的错误
  12. hadoop存储与分析
  13. 正电荷/内质网靶向性/蓝色/mCy-ER/绿色/开关型/CySeN花菁染料近红外荧光探针的制备
  14. Android apk瘦身
  15. 小米9se用twrp刷机时,出现persist挂载失败,导致系统启动不了的解决方法
  16. activiti会签功能
  17. html5游戏引擎国内文献综述,html5论文参考文献范例借鉴
  18. TP-Link WR703N升级64M内存+外接SMA天线+刷OpenWRT(1)硬件介绍
  19. 开放集识别(基于生成模型)
  20. BDT和XO的应用心得

热门文章

  1. 《AI 3.0》作者梅拉妮·米歇尔:今天的机器距离真正像人一样理解世界还有多远...
  2. 45 年编程经验告诉我的技术真相
  3. M理论能否成为解释一切的“万有理论”?
  4. java listview颜色_[摘]android listview选中某一行,成选中状态颜色高亮显示
  5. (pytorch-深度学习)循环神经网络的从零开始实现
  6. linux防火墙允许dns服务,Linux防火墙设置-DNS服务器篇
  7. C++面试/技巧(四)
  8. 怎么提高自己的系统架构水平
  9. Python C扩展的引用计数问题探讨
  10. 从零入门Serverless|一文搞懂函数计算及其工作原理