甘肃做高端网站的公司,教人做网站的视频,个人建购物网站怎么备案,网站建设域名跳转博客文章目录1. 版本兼容2. 导入依赖3. 配置4. 主页面5. 控制层6. 逻辑处理层7. pojo8. 工具类9. 常量类10. 前端页面项目开源地址1. 版本兼容
框架/组件版本SpringBoot2.6.1elasticsearch7.1.5
2. 导入依赖
parentgroupIdorg.springframework.boot/groupIdparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.6.1/versionrelativePath/ !-- lookup parent from repository --/parentdependencies!--解析网页--dependencygroupIdorg.jsoup/groupIdartifactIdjsoup/artifactIdversion1.14.3/version/dependencydependencygroupIdcom.alibaba/groupIdartifactIdfastjson/artifactIdversion1.2.78/version/dependency!--springboot 2.2.5 需要指定es版本默认引入es版本6.x--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-elasticsearch/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdscoperuntime/scopeoptionaltrue/optional/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency/dependencies3. 配置
server.port9090
spring.thymeleaf.cachefalse
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 ListMapString, 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 {ListContent 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 ListMapString, 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);// 解析结果ArrayListMapString, Object list new ArrayList();for (SearchHit documentFields : searchResponse.getHits().getHits()) {list.add(documentFields.getSourceAsMap());}return list;}// 2. 获取es中的数据实现基本搜索高亮功能public ListMapString, 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);// 解析结果ArrayListMapString, Object list new ArrayList();for (SearchHit hit : searchResponse.getHits().getHits()) {// 解析高亮的字段将原来的字段置换为我们高亮的字段即可MapString, HighlightField highlightFields hit.getHighlightFields();HighlightField title highlightFields.get(ESConst.HIGHLIGHT_TITLE);// 获取原来的结果MapString, 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 stylecolor: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:thhttp://www.thymeleaf.orgheadmeta charsetutf-8/titlegblfyJava-ES仿京东实战/titlelink relstylesheet th:href{/css/style.css}//headbody classpg
div classpage idappdiv idmallPage class mallist tmall- page-not-market !-- 头部搜索 --div idheader class header-list-appdiv classheaderLayoutdiv classheaderCon !-- Logo--h1 idmallLogoimg th:src{/images/jdlogo.png} alt/h1div classheader-extra!--搜索--div idmallSearch classmall-searchform namesearchTop classmallSearch-form clearfixfieldsetlegend天猫搜索/legenddiv classmallSearch-input clearfixdiv classs-combobox ids-combobox-685div classs-combobox-input-wrapinput v-modelkeyword typetext autocompleteoff valuedd idmqclasss-combobox-input aria-haspopuptrue/div/divbutton click.preventsearchKey typesubmit idsearchbtn搜索/button/div/fieldset/formul classrelKeyToplia狂神说Java/a/lilia狂神说前端/a/lilia狂神说Linux/a/lilia狂神说大数据/a/lilia狂神聊理财/a/li/ul/div/div/div/div/div!-- 商品详情页面 --div idcontentdiv classmain!-- 品牌分类 --form classnavAttrsFormdiv classattrs j_NavAttrs styledisplay:blockdiv classbrandAttr j_nav_branddiv classj_Brand attrdiv classattrKey品牌/divdiv classattrValuesul classav-collapse row-2lia href# gblfy /a/lilia href# Java /a/li/ul/div/div/div/div/form!-- 排序规则 --div classfilter clearfixa classfSort fSort-cur综合i classf-ico-arrow-d/i/aa classfSort人气i classf-ico-arrow-d/i/aa classfSort新品i classf-ico-arrow-d/i/aa classfSort销量i classf-ico-arrow-d/i/aa classfSort价格i classf-ico-triangle-mt/ii classf-ico-triangle-mb/i/a/div!-- 商品详情 --div classview grid-noskudiv classproduct v-foritem in resultsdiv classproduct-iWrap!--商品封面--div classproductImg-wrapa classproductImgimg :srcitem.img/a/div!--价格--p classproductPriceemb¥/b{{item.price}}/em/p!--标题--p classproductTitlea v-htmlitem.title /a/p!-- 店铺名 --div classproductShopspan店铺 gblfy Java /span/div!-- 成交信息 --p classproductStatusspan月成交em999笔/em/spanspan评价 a3/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
scriptnew 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