ElasticSearch實戰

ElasticSearch實戰

es: //www.elastic.co/cn/

kibana: //www.elastic.co/cn/kibana

鏈接://pan.baidu.com/s/1qmXNZBVGrcp0fuo9bBqrRA 提取碼:6zpo –來自百度網盤超級會員V5的分享 來自狂神公眾號

防京東商城搜索(高亮)

1、工程創建(springboot)

創建過程略

目錄結構

2、基本編碼

①導入依賴

  1. <properties>
  2. <java.version>1.8</java.version>
  3. <elasticsearch.version>7.6.1</elasticsearch.version>
  4. </properties>
  5. <dependencies>
  6. <!-- jsoup解析頁面 -->
  7. <!-- 解析網頁 爬影片可 研究tiko -->
  8. <dependency>
  9. <groupId>org.jsoup</groupId>
  10. <artifactId>jsoup</artifactId>
  11. <version>1.10.2</version>
  12. </dependency>
  13. <!-- fastjson -->
  14. <dependency>
  15. <groupId>com.alibaba</groupId>
  16. <artifactId>fastjson</artifactId>
  17. <version>1.2.70</version>
  18. </dependency>
  19. <!-- ElasticSearch -->
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  23. </dependency>
  24. <!-- thymeleaf -->
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  28. </dependency>
  29. <!-- web -->
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-web</artifactId>
  33. </dependency>
  34. <!-- devtools熱部署 -->
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-devtools</artifactId>
  38. <scope>runtime</scope>
  39. <optional>true</optional>
  40. </dependency>
  41. <!-- -->
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-configuration-processor</artifactId>
  45. <optional>true</optional>
  46. </dependency>
  47. <!-- lombok 需要安裝插件 -->
  48. <dependency>
  49. <groupId>org.projectlombok</groupId>
  50. <artifactId>lombok</artifactId>
  51. <optional>true</optional>
  52. </dependency>
  53. <!-- test -->
  54. <dependency>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-starter-test</artifactId>
  57. <scope>test</scope>
  58. </dependency>
  59. </dependencies>

②導入前端素材

③編寫 application.preperties配置文件

  1. # 更改埠,防止衝突
  2. server.port=9999
  3. # 關閉thymeleaf快取
  4. spring.thymeleaf.cache=false

④測試controller和view

  1. @Controller
  2. public class IndexController {
  3. @GetMapping({"/","index"})
  4. public String index(){
  5. return "index";
  6. }
  7. }

訪問 localhost:9999

到這裡可以先去編寫爬蟲,編寫之後,回到這裡

⑤編寫Config

  1. @Configuration
  2. public class ElasticSearchConfig {
  3. @Bean
  4. public RestHighLevelClient restHighLevelClient(){
  5. RestHighLevelClient client = new RestHighLevelClient(
  6. RestClient.builder(
  7. new HttpHost("127.0.0.1",9200,"http")
  8. )
  9. );
  10. return client;
  11. }
  12. }

⑥編寫service

因為是爬取的數據,那麼就不走Dao,以下編寫都不會編寫介面,開發中必須嚴格要求編寫

ContentService

  1. @Service
  2. public class ContentService {
  3. @Autowired
  4. private RestHighLevelClient restHighLevelClient;
  5. // 1、解析數據放入 es 索引中
  6. public Boolean parseContent(String keyword) throws IOException {
  7. // 獲取內容
  8. List<Content> contents = HtmlParseUtil.parseJD(keyword);
  9. // 內容放入 es 中
  10. BulkRequest bulkRequest = new BulkRequest();
  11. bulkRequest.timeout("2m"); // 可更具實際業務是指
  12. for (int i = 0; i < contents.size(); i++) {
  13. bulkRequest.add(
  14. new IndexRequest("jd_goods")
  15. .id(""+(i+1))
  16. .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
  17. );
  18. }
  19. BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
  20. restHighLevelClient.close();
  21. return !bulk.hasFailures();
  22. }
  23. // 2、根據keyword分頁查詢結果
  24. public List<Map<String, Object>> search(String keyword, Integer pageIndex, Integer pageSize) throws IOException {
  25. if (pageIndex < 0){
  26. pageIndex = 0;
  27. }
  28. SearchRequest jd_goods = new SearchRequest("jd_goods");
  29. // 創建搜索源建造者對象
  30. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  31. // 條件採用:精確查詢 通過keyword查欄位name
  32. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
  33. searchSourceBuilder.query(termQueryBuilder);
  34. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));// 60s
  35. // 分頁
  36. searchSourceBuilder.from(pageIndex);
  37. searchSourceBuilder.size(pageSize);
  38. // 高亮
  39. // ....
  40. // 搜索源放入搜索請求中
  41. jd_goods.source(searchSourceBuilder);
  42. // 執行查詢,返回結果
  43. SearchResponse searchResponse = restHighLevelClient.search(jd_goods, RequestOptions.DEFAULT);
  44. restHighLevelClient.close();
  45. // 解析結果
  46. SearchHits hits = searchResponse.getHits();
  47. List<Map<String,Object>> results = new ArrayList<>();
  48. for (SearchHit documentFields : hits.getHits()) {
  49. Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
  50. results.add(sourceAsMap);
  51. }
  52. // 返回查詢的結果
  53. return results;
  54. }
  55. }

⑦編寫controller

  1. @Controller
  2. public class ContentController {
  3. @Autowired
  4. private ContentService contentService;
  5. @ResponseBody
  6. @GetMapping("/parse/{keyword}")
  7. public Boolean parse(@PathVariable("keyword") String keyword) throws IOException {
  8. return contentService.parseContent(keyword);
  9. }
  10. @ResponseBody
  11. @GetMapping("/search/{keyword}/{pageIndex}/{pageSize}")
  12. public List<Map<String, Object>> parse(@PathVariable("keyword") String keyword,
  13. @PathVariable("pageIndex") Integer pageIndex,
  14. @PathVariable("pageSize") Integer pageSize) throws IOException {
  15. return contentService.search(keyword,pageIndex,pageSize);
  16. }
  17. }

⑧測試結果

1、解析數據放入 es 索引中

2、根據keyword分頁查詢結果

3、爬蟲(jsoup)

數據獲取:資料庫、消息隊列、爬蟲、…

①搜索京東搜索頁面,並分析頁面

  1. http://search.jd.com/search?keyword=java
頁面如下

審查頁面元素

頁面列表id:J_goodsList

目標元素:img、price、name

②爬取數據(獲取請求返回的頁面資訊,篩選出可用的)

創建HtmlParseUtil,並簡單編寫
  1. public class HtmlParseUtil {
  2. public static void main(String[] args) throws IOException {
  3. /// 使用前需要聯網
  4. // 請求url
  5. String url = "//search.jd.com/search?keyword=java";
  6. // 1.解析網頁(jsoup 解析返回的對象是瀏覽器Document對象)
  7. Document document = Jsoup.parse(new URL(url), 30000);
  8. // 使用document可以使用在js對document的所有操作
  9. // 2.獲取元素(通過id)
  10. Element j_goodsList = document.getElementById("J_goodsList");
  11. // 3.獲取J_goodsList ul 每一個 li
  12. Elements lis = j_goodsList.getElementsByTag("li");
  13. // 4.獲取li下的 img、price、name
  14. for (Element li : lis) {
  15. String img = li.getElementsByTag("img").eq(0).attr("src");// 獲取li下 第一張圖片
  16. String name = li.getElementsByClass("p-name").eq(0).text();
  17. String price = li.getElementsByClass("p-price").eq(0).text();
  18. System.out.println("=======================");
  19. System.out.println("img : " + img);
  20. System.out.println("name : " + name);
  21. System.out.println("price : " + price);
  22. }
  23. }
  24. }

運行結果

原因是啥?

一般圖片特別多的網站,所有的圖片都是通過延遲載入的

  1. // 列印標籤內容
  2. Elements lis = j_goodsList.getElementsByTag("li");
  3. System.out.println(lis);

列印所有li標籤,發現img標籤中並沒有屬性src的設置,只是data-lazy-ing設置圖片載入的地址

創建HtmlParseUtil、改寫
  • 更改圖片獲取屬性為 data-lazy-img

  • 與實體類結合,實體類如下

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. public class Content implements Serializable {
    5. private static final long serialVersionUID = -8049497962627482693L;
    6. private String name;
    7. private String img;
    8. private String price;
    9. }
  • 封裝為方法

  1. public class HtmlParseUtil {
  2. public static void main(String[] args) throws IOException {
  3. System.out.println(parseJD("java"));
  4. }
  5. public static List<Content> parseJD(String keyword) throws IOException {
  6. /// 使用前需要聯網
  7. // 請求url
  8. String url = "//search.jd.com/search?keyword=" + keyword;
  9. // 1.解析網頁(jsoup 解析返回的對象是瀏覽器Document對象)
  10. Document document = Jsoup.parse(new URL(url), 30000);
  11. // 使用document可以使用在js對document的所有操作
  12. // 2.獲取元素(通過id)
  13. Element j_goodsList = document.getElementById("J_goodsList");
  14. // 3.獲取J_goodsList ul 每一個 li
  15. Elements lis = j_goodsList.getElementsByTag("li");
  16. // System.out.println(lis);
  17. // 4.獲取li下的 img、price、name
  18. // list存儲所有li下的內容
  19. List<Content> contents = new ArrayList<Content>();
  20. for (Element li : lis) {
  21. // 由於網站圖片使用懶載入,將src屬性替換為data-lazy-img
  22. String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img");// 獲取li下 第一張圖片
  23. String name = li.getElementsByClass("p-name").eq(0).text();
  24. String price = li.getElementsByClass("p-price").eq(0).text();
  25. // 封裝為對象
  26. Content content = new Content(name,img,price);
  27. // 添加到list中
  28. contents.add(content);
  29. }
  30. // System.out.println(contents);
  31. // 5.返回 list
  32. return contents;
  33. }
  34. }

結果展示

4、搜索高亮

在3、的基礎上添加內容

①ContentService

  1. // 3、 在2的基礎上進行高亮查詢
  2. public List<Map<String, Object>> highlightSearch(String keyword, Integer pageIndex, Integer pageSize) throws IOException {
  3. SearchRequest searchRequest = new SearchRequest("jd_goods");
  4. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  5. // 精確查詢,添加查詢條件
  6. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
  7. searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
  8. searchSourceBuilder.query(termQueryBuilder);
  9. // 分頁
  10. searchSourceBuilder.from(pageIndex);
  11. searchSourceBuilder.size(pageSize);
  12. // 高亮 =========
  13. HighlightBuilder highlightBuilder = new HighlightBuilder();
  14. highlightBuilder.field("name");
  15. highlightBuilder.preTags("<span style='color:red'>");
  16. highlightBuilder.postTags("</span>");
  17. searchSourceBuilder.highlighter(highlightBuilder);
  18. // 執行查詢
  19. searchRequest.source(searchSourceBuilder);
  20. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  21. // 解析結果 ==========
  22. SearchHits hits = searchResponse.getHits();
  23. List<Map<String, Object>> results = new ArrayList<>();
  24. for (SearchHit documentFields : hits.getHits()) {
  25. // 使用新的欄位值(高亮),覆蓋舊的欄位值
  26. Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
  27. // 高亮欄位
  28. Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
  29. HighlightField name = highlightFields.get("name");
  30. // 替換
  31. if (name != null){
  32. Text[] fragments = name.fragments();
  33. StringBuilder new_name = new StringBuilder();
  34. for (Text text : fragments) {
  35. new_name.append(text);
  36. }
  37. sourceAsMap.put("name",new_name.toString());
  38. }
  39. results.add(sourceAsMap);
  40. }
  41. return results;
  42. }

②ContentController

  1. @ResponseBody
  2. @GetMapping("/h_search/{keyword}/{pageIndex}/{pageSize}")
  3. public List<Map<String, Object>> highlightParse(@PathVariable("keyword") String keyword,
  4. @PathVariable("pageIndex") Integer pageIndex,
  5. @PathVariable("pageSize") Integer pageSize) throws IOException {
  6. return contentService.highlightSearch(keyword,pageIndex,pageSize);
  7. }

③結果展示

5、前後端分離(簡單使用Vue)

刪除Controller 方法上的 @ResponseBody註解

①下載並引入Vue.min.js和axios.js

如果安裝了nodejs,可以按如下步驟,沒有可以到後面素材處下載

  1. npm install vue
  2. npm install axios

②修改靜態頁面

引入js
  1. <script th:src="@{/js/vue.min.js}"></script>
  2. <script th:src="@{/js/axios.min.js}"></script>
修改後的index.html
  1. <!DOCTYPE html>
  2. <html xmlns:th="//www.thymeleaf.org">
  3. <head>
  4. <meta charset="utf-8"/>
  5. <title>狂神說Java-ES仿京東實戰</title>
  6. <link rel="stylesheet" th:href="@{/css/style.css}"/>
  7. <script th:src="@{/js/jquery.min.js}"></script>
  8. </head>
  9. <body class="pg">
  10. <div class="page">
  11. <div id="app" class=" mallist tmall- page-not-market ">
  12. <!-- 頭部搜索 -->
  13. <div id="header" class=" header-list-app">
  14. <div class="headerLayout">
  15. <div class="headerCon ">
  16. <!-- Logo-->
  17. <h1 id="mallLogo">
  18. <img th:src="@{/images/jdlogo.png}" alt="">
  19. </h1>
  20. <div class="header-extra">
  21. <!--搜索-->
  22. <div id="mallSearch" class="mall-search">
  23. <form name="searchTop" class="mallSearch-form clearfix">
  24. <fieldset>
  25. <legend>天貓搜索</legend>
  26. <div class="mallSearch-input clearfix">
  27. <div class="s-combobox" id="s-combobox-685">
  28. <div class="s-combobox-input-wrap">
  29. <input v-model="keyword" type="text" autocomplete="off" id="mq"
  30. class="s-combobox-input" aria-haspopup="true">
  31. </div>
  32. </div>
  33. <button type="submit" @click.prevent="searchKey" id="searchbtn">搜索</button>
  34. </div>
  35. </fieldset>
  36. </form>
  37. <ul class="relKeyTop">
  38. <li><a>狂神說Java</a></li>
  39. <li><a>狂神說前端</a></li>
  40. <li><a>狂神說Linux</a></li>
  41. <li><a>狂神說大數據</a></li>
  42. <li><a>狂神聊理財</a></li>
  43. </ul>
  44. </div>
  45. </div>
  46. </div>
  47. </div>
  48. </div>
  49. <!-- 商品詳情頁面 -->
  50. <div id="content">
  51. <div class="main">
  52. <!-- 品牌分類 -->
  53. <form class="navAttrsForm">
  54. <div class="attrs j_NavAttrs" style="display:block">
  55. <div class="brandAttr j_nav_brand">
  56. <div class="j_Brand attr">
  57. <div class="attrKey">
  58. 品牌
  59. </div>
  60. <div class="attrValues">
  61. <ul class="av-collapse row-2">
  62. <li><a href="#"> 狂神說 </a></li>
  63. <li><a href="#"> Java </a></li>
  64. </ul>
  65. </div>
  66. </div>
  67. </div>
  68. </div>
  69. </form>
  70. <!-- 排序規則 -->
  71. <div class="filter clearfix">
  72. <a class="fSort fSort-cur">綜合<i class="f-ico-arrow-d"></i></a>
  73. <a class="fSort">人氣<i class="f-ico-arrow-d"></i></a>
  74. <a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
  75. <a class="fSort">銷量<i class="f-ico-arrow-d"></i></a>
  76. <a class="fSort">價格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
  77. </div>
  78. <!-- 商品詳情 -->
  79. <div class="view grid-nosku" >
  80. <div class="product" v-for="result in results">
  81. <div class="product-iWrap">
  82. <!--商品封面-->
  83. <div class="productImg-wrap">
  84. <a class="productImg">
  85. <img :src="result.img">
  86. </a>
  87. </div>
  88. <!--價格-->
  89. <p class="productPrice">
  90. <em v-text="result.price"></em>
  91. </p>
  92. <!--標題-->
  93. <p class="productTitle">
  94. <a v-html="result.name"></a>
  95. </p>
  96. <!-- 店鋪名 -->
  97. <div class="productShop">
  98. <span>店鋪: 狂神說Java </span>
  99. </div>
  100. <!-- 成交資訊 -->
  101. <p class="productStatus">
  102. <span>月成交<em>999筆</em></span>
  103. <span>評價 <a>3</a></span>
  104. </p>
  105. </div>
  106. </div>
  107. </div>
  108. </div>
  109. </div>
  110. </div>
  111. </div>
  112. <script th:src="@{/js/vue.min.js}"></script>
  113. <script th:src="@{/js/axios.min.js}"></script>
  114. <script>
  115. new Vue({
  116. el:"#app",
  117. data:{
  118. "keyword": '', // 搜索的關鍵字
  119. "results":[] // 後端返回的結果
  120. },
  121. methods:{
  122. searchKey(){
  123. var keyword = this.keyword;
  124. console.log(keyword);
  125. axios.get('h_search/'+keyword+'/0/20').then(response=>{
  126. console.log(response.data);
  127. this.results=response.data;
  128. })
  129. }
  130. }
  131. });
  132. </script>
  133. </body>
  134. </html>
測試

安裝包及前端素材

鏈接://pan.baidu.com/s/1M5uWdYsCZyzIAOcgcRkA_A
提取碼:qk8p
複製這段內容後打開百度網盤手機App,操作更方便哦

疑惑:

1、使用term(精確查詢)時,我發現三個問題,問題如下:

  • 欄位值必須是一個詞(索引中存在的詞),才能匹配

    • 問題:中文字元串,term查詢時無法查詢到數據(比如,「編程」兩字在文檔中存在,但是搜索不到)

    • 原因:索引為配置中文分詞器(默認使用standard,即所有中文字元串都會被切分為單個中文漢字作為單詞),所以沒有超過1個漢字的詞,也就無法匹配,進而查不到數據

    • 解決:創建索引時配置中文分詞器,如

      1. PUT example
      2. {
      3. "mappings": {
      4. "properties": {
      5. "name":{
      6. "type": "text",
      7. "analyzer": "ik_max_word" // ik分詞器
      8. }
      9. }
      10. }
      11. }
  • 查詢的英文字元只能是小寫,大寫都無效

  • 查詢時英文單詞必須是完整的