国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

121.【ElasticSearch偽京東搜索】

這篇具有很好參考價值的文章主要介紹了121.【ElasticSearch偽京東搜索】。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

(一)、搭建環(huán)境

0.啟動ElasticSearch和head和kblian

(1).啟動EslaticSearch (9200)

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(2).啟動Es-head (9101)

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(3).啟動 Kibana (5602)

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

1.項目依賴

<?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.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.jsxs</groupId>
    <artifactId>Jsxs-es-JD</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Jsxs-es-JD</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <!--    自己定義es版本依賴,保證和本地一致    -->
        <elasticsearch.version>7.6.2</elasticsearch.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>2.7.9</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--   引入我們的JSON包     -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.26</version>
        </dependency>
        <!--      引入Thymeleaf啟動器  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.7.7</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.啟動測試

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(二)、爬蟲

1.數(shù)據(jù)從哪里獲取

  • 數(shù)據(jù)庫獲取。
  • 消息隊列中獲取中。
  • 爬蟲

2.導(dǎo)入爬蟲的依賴

tika包解析電影的.jsoup解析網(wǎng)頁

<!--        jsoup解析網(wǎng)頁-->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.2</version>
</dependency>

3.編寫爬蟲工具類

(1).實體類
package com.jsxs.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author Jsxs
 * @Date 2023/6/30 13:06
 * @PackageName:com.jsxs.pojo
 * @ClassName: Content
 * @Description: TODO
 * @Version 1.0
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Content {
    private String title;
    private String img;
    private String price;

}

(2).工具類編寫 (已廢棄?)
package com.jsxs.utils;

import com.jsxs.pojo.Content;
import org.elasticsearch.common.recycler.Recycler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Jsxs
 * @Date 2023/6/30 12:40
 * @PackageName:com.jsxs.utils
 * @ClassName: HtmlParseUtil
 * @Description: TODO
 * @Version 1.0
 */
@Component
public class HtmlParseUtil {

    public List<Content> parseJD(String keywords) throws Exception {
        // 1.獲得請求
        String url = "https://search.jd.com/Search?keyword="+keywords;
        // 2.解析網(wǎng)頁 返回的document對象就是瀏覽器的Document對象
        Document document = Jsoup.parse(new URL(url), 3000);
        // 3.利用js的Document對象進(jìn)行操作  ->獲取商品整個html頁面
        Element element = document.getElementById("J_goodsList");
        // 4.獲取所有的li元素 是一個集合。
        Elements elements = element.getElementsByTag("li");

        // 創(chuàng)建一個鏈表,用于存放我們爬取到的信息
        ArrayList<Content> contents = new ArrayList<>();

        // 5.獲取元素中的各個內(nèi)容
        for (Element li : elements) {
            // 獲取圖片  這里面加上attr目的是懶加載。
            String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img"); // 爬取懶加載的圖片
            // 獲取價格
            String price = li.getElementsByClass("p-price").eq(0).text();
            // 獲取上坪的價格
            String title = li.getElementsByClass("p-name").eq(0).text();
            // 存放我們爬取到的信息
            contents.add(new Content(title,img,price));
        }
        return contents;
    }

    public static void main(String[] args) throws Exception {
        for (Content java : new HtmlParseUtil().parseJD("碼出高效")) {
            System.out.println(java);
        }
    }
}

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(3).工具類編寫 - 解決京東防護(hù)

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

package com.jsxs.utils;

import com.jsxs.pojo.Content;
import org.elasticsearch.common.recycler.Recycler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Jsxs
 * @Date 2023/6/30 12:40
 * @PackageName:com.jsxs.utils
 * @ClassName: HtmlParseUtil
 * @Description: TODO
 * @Version 1.0
 */
@Component
public class HtmlParseUtil {

    public List<Content> parseJD(String keywords) throws Exception {
        // 1.獲得請求
        String url = "https://search.jd.com/Search?keyword="+keywords;
        System.out.println(url);

        // 設(shè)置cookie
        Map<String, String> cookies = new HashMap<String, String>();
        cookies.put("thor", "35C0A430DD191386DC5C6605461B820975545DB4E7B5F6CD3717B58D8F3B4CF548ED5F724A0CFF52528BCC4C1382E38FDD39F7714D356D73C80DBC98E351588E74A77B0CB8B5348847042F8AB08B9D4BC87539F45579E34614217BFD76FCEEBEC829173EEA7B4D51FAA162DD62B98376375C46B24B2FAAC96C7C733BC0F3B6165DB89F97C62170FD0838A7F72212B95CD38FC61DEF2B38C36A1F8C252C2809C8");
        //  2.解析網(wǎng)頁 返回的document對象就是瀏覽器的Document對象
        Document document = Jsoup.connect(url).cookies(cookies).get();
        // 3.利用js的Document對象進(jìn)行操作  ->獲取商品整個html頁面
        Element element = document.getElementById("J_goodsList");
        System.out.println("***************"+element);
        // 4.獲取所有的li元素 是一個集合。
        Elements elements = element.getElementsByTag("li");

        // 創(chuàng)建一個鏈表,用于存放我們爬取到的信息
        ArrayList<Content> contents = new ArrayList<>();

        // 5.獲取元素中的各個內(nèi)容
        for (Element li : elements) {
            // 獲取圖片  這里面加上attr目的是懶加載。
            String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img"); // 爬取懶加載的圖片
            // 獲取價格
            String price = li.getElementsByClass("p-price").eq(0).text();
            // 獲取上坪的價格
            String title = li.getElementsByClass("p-name").eq(0).text();
            // 存放我們爬取到的信息
            contents.add(new Content(title,img,price));
        }
        return contents;
    }

    public static void main(String[] args) throws Exception {
        for (Content java : new HtmlParseUtil().parseJD("java")) {
            System.out.println(java);
        }
    }
}

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

4.導(dǎo)入配置類

package com.jsxs.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;

/**
 * @Author Jsxs
 * @Date 2023/6/30 14:13
 * @PackageName:com.jsxs.config
 * @ClassName: ElasticSearchClientConfig
 * @Description: TODO
 * @Version 1.0
 */
@Configuration
public class ElasticSearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }
}

(三)、將爬取到的數(shù)據(jù)存放到ES

1.創(chuàng)建Service層

ContentService.java

package com.jsxs.service;

import com.alibaba.fastjson2.JSON;
import com.jsxs.pojo.Content;
import com.jsxs.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Jsxs
 * @Date 2023/6/30 14:08
 * @PackageName:com.jsxs.service
 * @ClassName: ContentService
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class ContentService {

    @Resource
    RestHighLevelClient client;

    public static void main(String[] args) throws Exception {
        System.out.println(new ContentService().parseContent("java"));
    }

    // 1.解析數(shù)據(jù)放入我們的es索引中
    public Boolean parseContent(String keywords) throws Exception {
        List<Content> list = new HtmlParseUtil().parseJD(keywords);
        // 2. 把查詢到的數(shù)據(jù)批量放入es中去
        BulkRequest bulkRequest = new BulkRequest();
        // 3.設(shè)置超時的時間
        bulkRequest.timeout("2s");
        // 4.創(chuàng)建一個新的索引名字叫做 jd_goods ??運行第二次的時候,要把創(chuàng)建庫的語句給刪除掉
        CreateIndexRequest request = new CreateIndexRequest("jd_goods");
        client.indices().create(request, RequestOptions.DEFAULT);
        // 5.批量插入到數(shù)據(jù)中 并設(shè)置id。
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
                            .id(""+i+1)
                            .source(JSON.toJSONString(list.get(i)), XContentType.JSON)

            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        // 如果沒有失敗就返回成功
        return !bulk.hasFailures();
    }
}

2.進(jìn)行測試 (ES是否存放成功)

package com.jsxs;

import com.jsxs.service.ContentService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
class JsxsEsJdApplicationTests {

    @Resource
    ContentService contentService;

    @Test
    void contextLoads() throws Exception {
        System.out.println(contentService.parseContent("java"));
    }

}

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(四)、從ES中分頁讀取數(shù)據(jù) (關(guān)鍵字不能為中文)

切記我們只能讀取到我們ES中存放的數(shù)據(jù),假如進(jìn)行查詢沒有存放在ES的數(shù)據(jù),我們就會得到空的數(shù)據(jù)。

1.從ES中讀取數(shù)據(jù)

(1).ContentService 層
package com.jsxs.service;

import com.alibaba.fastjson2.JSON;
import com.jsxs.pojo.Content;
import com.jsxs.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.client.indices.CreateIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Jsxs
 * @Date 2023/6/30 14:08
 * @PackageName:com.jsxs.service
 * @ClassName: ContentService
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class ContentService {

    @Resource
    RestHighLevelClient client;

    // 1.解析數(shù)據(jù)放入我們的es索引中
    public Boolean parseContent(String keywords) throws Exception {
        List<Content> list = new HtmlParseUtil().parseJD(keywords);
        // 2. 把查詢到的數(shù)據(jù)批量放入es中去
        BulkRequest bulkRequest = new BulkRequest();
        // 3.設(shè)置超時的時間
        bulkRequest.timeout("2s");
        // 4.創(chuàng)建一個新的索引名字叫做 jd_goods
//        CreateIndexRequest request = new CreateIndexRequest("jd_goods");
//        client.indices().create(request, RequestOptions.DEFAULT);
        // 5.批量插入到數(shù)據(jù)中 并設(shè)置id。
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
                            .id(i+1+"")
                            .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        // 如果沒有失敗就返回成功
        return !bulk.hasFailures();
    }

    // 2. 從ES中進(jìn)行搜索內(nèi)容
    public  List<Map<String,Object>> searchesPage(String keywords,int pageNo,int pageSize) throws IOException {

        if (pageNo<=1){
            pageNo=1;
        }

        // 1.條件搜索  ?
        SearchRequest request = new SearchRequest("jd_goods");
         // 2.構(gòu)建搜索條件  ??
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 3.分頁  ???
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        // 4. 精確匹配: 第一個參數(shù)是參數(shù)列名,第二個參數(shù)是 搜索的內(nèi)容 ????
        TermQueryBuilder query = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 5.執(zhí)行搜索 ?????
        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT); //這里會得到一個結(jié)果

        // 6.解析結(jié)果  ??????
        SearchHits hits = searchResponse.getHits(); // 這里會獲取到一個對象,對象里面包含著一個hits數(shù)組
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        System.out.println(list);
        return list;
    }
}

(2).ContentController 控制層
package com.jsxs.controller;

import com.jsxs.service.ContentService;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author Jsxs
 * @Date 2023/6/30 14:08
 * @PackageName:com.jsxs.controller
 * @ClassName: ContentController
 * @Description: TODO
 * @Version 1.0
 */
@RestController
public class ContentController {

    @Resource
    private ContentService contentService;

    // 普通查詢數(shù)據(jù)
    @GetMapping("/parse/{keywords}")
    public Boolean parse(@PathVariable("keywords") String keywords) throws Exception {
        return contentService.parseContent(keywords);
    }

    // 分頁查詢數(shù)據(jù)加高亮
    @GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
    public List<Map<String,Object>> search(@PathVariable("keyword") String keyword,@PathVariable("pageNo") int pageNo,@PathVariable("pageSize") int pageSize) throws IOException {
        return contentService.searchesPage(keyword,pageNo,pageSize);
    }

    //


}

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

2.錯誤演示 (讀取es中沒有的數(shù)據(jù))

1. 我們在ES中存放的關(guān)鍵字是 java 而我們讀取的關(guān)鍵字是 夏裝
121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)
2. 讀取不到夏裝的數(shù)據(jù)
121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(五)、前后端交互

1.新增兩個js

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

2.修改原本的頁面信息

(1).修改的前端頁面

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8"/>
    <title>狂神說Java-ES仿京東實戰(zhàn)</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="keywords" 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>狂神說大數(shù)據(jù)</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>

                <!-- 排序規(guī)則 -->
                <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><b></b>{{result.price}}</em>
                            </p>
                            <!--標(biāo)題-->
                            <p class="productTitle">
                                <a> {{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>

<!--前端使用vue,完成前后端分離  ???-->
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/vue.js}"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            keywords: '', //搜索的關(guān)鍵字
            results:[] //搜索的結(jié)果
        },
        methods: {
            searchKey() {
                var keyword = this.keywords;
                console.log(keyword);
                //對接后端的接口,異步獲取查詢到的值
                axios.get('search/' + keyword + "/1/10").then(response => {
                    console.log(response);
                    this.results = response.data; // 綁定數(shù)據(jù)
                })
            }
        }
    })
</script>

</body>
</html>

3.在批量插入數(shù)據(jù)的時候把id給注釋掉

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

4.運行測試成功

讀取的都是es中的數(shù)據(jù),假如es中沒有數(shù)據(jù)的話,就會查不到
121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)
121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

(六)、實現(xiàn)搜索的高亮

1.實現(xiàn)搜索高亮

(1).ContentService 層
package com.jsxs.service;

import com.alibaba.fastjson2.JSON;
import com.jsxs.pojo.Content;
import com.jsxs.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.client.indices.CreateIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
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.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Jsxs
 * @Date 2023/6/30 14:08
 * @PackageName:com.jsxs.service
 * @ClassName: ContentService
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class ContentService {

    @Resource
    RestHighLevelClient client;

    // 1.解析數(shù)據(jù)放入我們的es索引中
    public Boolean parseContent(String keywords) throws Exception {
        List<Content> list = new HtmlParseUtil().parseJD(keywords);
        // 2. 把查詢到的數(shù)據(jù)批量放入es中去
        BulkRequest bulkRequest = new BulkRequest();
        // 3.設(shè)置超時的時間
        bulkRequest.timeout("2s");
        // 4.創(chuàng)建一個新的索引名字叫做 jd_goods
//        CreateIndexRequest request = new CreateIndexRequest("jd_goods");
//        client.indices().create(request, RequestOptions.DEFAULT);
        // 5.批量插入到數(shù)據(jù)中 并設(shè)置id。
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
//                            .id(i+1+"")   盡量去掉id可以
                            .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        // 如果沒有失敗就返回成功
        return !bulk.hasFailures();
    }

    // 2. 獲取ES數(shù)據(jù)實現(xiàn)基本的搜索功能
    public  List<Map<String,Object>> searchesPage(String keywords,int pageNo,int pageSize) throws IOException {

        if (pageNo<=1){
            pageNo=1;
        }

        // 1.條件搜索
        SearchRequest request = new SearchRequest("jd_goods");
         // 2.構(gòu)建搜索條件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 3.分頁
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        // 4. 精確匹配: 第一個參數(shù)是參數(shù)列名,第二個參數(shù)是 搜索的內(nèi)容
        TermQueryBuilder query = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 5.執(zhí)行搜索
        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT); //這里會得到一個結(jié)果

        // 6.解析結(jié)果
        SearchHits hits = searchResponse.getHits(); // 這里會獲取到一個對象,對象里面包含著一個hits數(shù)組
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    // 3.獲取ES數(shù)據(jù)實現(xiàn)高亮+分頁
    public  List<Map<String,Object>> searchesPageHight(String keywords,int pageNo,int pageSize) throws IOException {

        if (pageNo<=1){
            pageNo=1;
        }

        // 1.條件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        // 2.構(gòu)建搜索條件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 3.分頁
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);


        // 4. 精確匹配: 第一個參數(shù)是參數(shù)列名,第二個參數(shù)是 搜索的內(nèi)容
        TermQueryBuilder query = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        // 5.配置高亮設(shè)置 ?
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false); //一個文本中多個關(guān)鍵字只高亮一個關(guān)鍵字
        highlightBuilder.field("title"); //對那個屬性進(jìn)行高亮
        highlightBuilder.preTags("<span style='color:yellow'>"); //文本的前標(biāo)簽
        highlightBuilder.postTags("</span>"); // 文本的后標(biāo)簽
        // 6.執(zhí)行高亮設(shè)置 ??
        searchSourceBuilder.highlighter(highlightBuilder);


        // 7.執(zhí)行搜索
        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT); //這里會得到一個結(jié)果

        // 8.將原本文本解析成高亮文本 ???
        SearchHits hits = searchResponse.getHits(); // 這里會獲取到一個對象,對象里面包含著一個hits數(shù)組
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();  // 原來的結(jié)果
            // 解析高亮的字段,將原來的字段換為我們高亮的字段即可
            if (title!=null){
                Text[] fragments = title.fragments();
                String n_title="";
                for (Text text : fragments) {
                    n_title+=text;
                }
                sourceAsMap.put("title",n_title);  //高亮字段替換掉原來的內(nèi)容即可。
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
(2).ContentController 層
package com.jsxs.controller;

import com.jsxs.service.ContentService;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author Jsxs
 * @Date 2023/6/30 14:08
 * @PackageName:com.jsxs.controller
 * @ClassName: ContentController
 * @Description: TODO
 * @Version 1.0
 */
@RestController
public class ContentController {

    @Resource
    private ContentService contentService;

    // 普通查詢數(shù)據(jù)
    @GetMapping("/parse/{keywords}")
    public Boolean parse(@PathVariable("keywords") String keywords) throws Exception {
        return contentService.parseContent(keywords);
    }

    // 分頁查詢數(shù)據(jù)加高亮
    @GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
    public List<Map<String,Object>> search(@PathVariable("keyword") String keyword,@PathVariable("pageNo") int pageNo,@PathVariable("pageSize") int pageSize) throws IOException {
        return contentService.searchesPageHight(keyword,pageNo,pageSize);
    }
}

(3).我們發(fā)現(xiàn)結(jié)果沒有進(jìn)行解析

121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)

2.解決結(jié)果沒有解析

vue 頁面沒有被html解析,我們只需要html解析即可。
121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)
121.【ElasticSearch偽京東搜索】,elasticsearch,jenkins,大數(shù)據(jù)文章來源地址http://www.zghlxwxcb.cn/news/detail-520801.html

到了這里,關(guān)于121.【ElasticSearch偽京東搜索】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 向量數(shù)據(jù)庫:使用Elasticsearch實現(xiàn)向量數(shù)據(jù)存儲與搜索

    Here’s the table of contents: ??Elasticsearch在7.x的版本中支持 向量檢索 。在向量函數(shù)的計算過程中,會對所有匹配的文檔進(jìn)行線性掃描。因此,查詢預(yù)計時間會隨著匹配文檔的數(shù)量線性增長。出于這個原因,建議使用查詢參數(shù)來限制匹配文檔的數(shù)量(類似二次查找的邏輯,先使

    2024年02月07日
    瀏覽(98)
  • 搜索引擎(大數(shù)據(jù)檢索)論述[elasticsearch原理相關(guān)]

    搜索引擎(大數(shù)據(jù)檢索)論述[elasticsearch原理相關(guān)]

    首先需要大致知道搜索引擎有大致幾類:1.全文搜索引擎 2.垂直搜索引擎 3.類目搜索引擎等。 1.全文搜索引擎:是全文本覆蓋的,百度,google等都是全文本搜索,就是我搜一個詞項“方圓”,那么這個詞項可以是數(shù)字平方的概念,可以是一個人名,可以是一首歌等,所有的相

    2023年04月08日
    瀏覽(31)
  • elasticsearch[四]-數(shù)據(jù)聚合排序查詢、搜索框自動補(bǔ)全、數(shù)據(jù)同步、集群

    elasticsearch[四]-數(shù)據(jù)聚合排序查詢、搜索框自動補(bǔ)全、數(shù)據(jù)同步、集群

    **聚合(aggregations)**可以讓我們極其方便的實現(xiàn)對數(shù)據(jù)的統(tǒng)計、分析、運算。例如: 什么品牌的手機(jī)最受歡迎? 這些手機(jī)的平均價格、最高價格、最低價格? 這些手機(jī)每月的銷售情況如何? 實現(xiàn)這些統(tǒng)計功能的比數(shù)據(jù)庫的 sql 要方便的多,而且查詢速度非???,可以實現(xiàn)近

    2024年01月19日
    瀏覽(18)
  • Elasticsearch:語義搜索、知識圖和向量數(shù)據(jù)庫概述

    Elasticsearch:語義搜索、知識圖和向量數(shù)據(jù)庫概述

    結(jié)合對你自己的私有數(shù)據(jù)執(zhí)行語義搜索的概述 語義搜索是一種使用自然語言處理算法來理解單詞和短語的含義和上下文以提供更準(zhǔn)確的搜索結(jié)果的搜索技術(shù)。 這種方法基于這樣的想法:搜索引擎不僅應(yīng)該匹配查詢中的,還應(yīng)該嘗試?yán)斫庥脩羲阉鞯囊鈭D以及所使用的單

    2024年02月16日
    瀏覽(30)
  • 使用 LangChain 和 Elasticsearch 對私人數(shù)據(jù)進(jìn)行人工智能搜索

    使用 LangChain 和 Elasticsearch 對私人數(shù)據(jù)進(jìn)行人工智能搜索

    關(guān)于本博文的所有代碼可以在地址下載:GitHub - liu-xiao-guo/python-vector-private 我將在本博文中其中深入研究人工智能和向量嵌入的深水區(qū)。 ChatGPT 令人大開眼界,但有一個主要問題。 這是一個封閉的托管系統(tǒng)。 在一個被大型網(wǎng)絡(luò)公司改變的世界里生活了二十年之后,我們作為人

    2024年02月07日
    瀏覽(29)
  • 【ElasticSearch】大數(shù)據(jù)量情況下的前綴、中綴實時搜索方案

    【ElasticSearch】大數(shù)據(jù)量情況下的前綴、中綴實時搜索方案

    業(yè)務(wù)開發(fā)中經(jīng)常會遇到這樣一種情況,用戶在搜索框輸入時要實時展示搜索相關(guān)的結(jié)果。要實現(xiàn)這個場景常用的方案有Completion Suggester、search_as_you_type。那么這兩種方式有什么區(qū)別呢?一起來了解下。 數(shù)據(jù)量:9000w+ es版本:7.10.1 腳本執(zhí)行工具:kibana 1.Completion Suggester是基于前

    2024年02月16日
    瀏覽(23)
  • ElasticSearch - 根據(jù)經(jīng)緯度,簡單搜索指定距離范圍內(nèi)的數(shù)據(jù)

    ElasticSearch - 根據(jù)經(jīng)緯度,簡單搜索指定距離范圍內(nèi)的數(shù)據(jù)

    ES的地圖檢索方式 ES支持的地圖檢索方式有以下幾種; geo_distance geo_bounding_box geo_polygon 1、 geo_distance :直線距離檢索,如給定點A,要求返回地圖上距離點A三千米的商家(點外賣場景) 2、查找索引內(nèi)距離北京站(116.433733,39.908404)3000米內(nèi)的點 geo_distance涉及的參數(shù)如下 location:確

    2024年02月14日
    瀏覽(17)
  • 基于Elasticsearch與Hbase組合框架的大數(shù)據(jù)搜索引擎

    基于Elasticsearch與Hbase組合框架的大數(shù)據(jù)搜索引擎

    本項目為學(xué)校大數(shù)據(jù)工程實訓(xùn)項目,共開發(fā)4周,答辯成績不錯。代碼倉庫放文章尾,寫的不好,代碼僅供參考。 對于結(jié)構(gòu)化數(shù)據(jù) ,因為它們具有特定的結(jié)構(gòu),所以我們一般都是可以通過關(guān)系型數(shù)據(jù)庫(MySQL,Oracle 等)的二維表(Table)的方式存儲和搜索,也可以建立索引。

    2024年02月09日
    瀏覽(23)
  • Elasticsearch集群搭建、數(shù)據(jù)分片以及位置坐標(biāo)實現(xiàn)附近的人搜索

    es使用兩種不同的方式來發(fā)現(xiàn)對方: 廣播 單播 也可以同時使用兩者,但默認(rèn)的廣播,單播需要已知節(jié)點列表來完成 當(dāng)es實例啟動的時候,它發(fā)送了廣播的ping請求到地址 224.2.2.4:54328 。而其他的es實例使用同樣的集群名稱響應(yīng)了這個請求。 一般這個默認(rèn)的集群名稱就是上面的

    2024年02月06日
    瀏覽(25)
  • Elasticsearch (ES) 搜索引擎: 數(shù)據(jù)類型、動態(tài)映射、多類型(子字段)

    原文鏈接:https://xiets.blog.csdn.net/article/details/132348634 版權(quán)聲明:原創(chuàng)文章禁止轉(zhuǎn)載 專欄目錄:Elasticsearch 專欄(總目錄) ES 映射字段的 數(shù)據(jù)類型 ,官網(wǎng)文檔參考:Field data types。 下面是 ES 常用的一些基本數(shù)據(jù)類型。 字符串 類型: keyword :類型。 text :文本類型。

    2024年03月23日
    瀏覽(38)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包