日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

SpringBoot2.6.1 elasticsearch7.1.5 Vue

發布時間:2024/9/27 vue 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot2.6.1 elasticsearch7.1.5 Vue 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.



文章目錄

            • 1. 版本兼容
            • 2. 導入依賴
            • 3. 配置
            • 4. 主頁面
            • 5. 控制層
            • 6. 邏輯處理層
            • 7. pojo
            • 8. 工具類
            • 9. 常量類
            • 10. 前端頁面
            • 項目開源地址

1. 版本兼容
框架/組件版本
SpringBoot2.6.1
elasticsearch7.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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。