121.【ElasticSearch伪京东搜索】

news2024/10/6 14:24:19

模仿京东搜索

  • (一)、搭建环境
    • 0.启动ElasticSearch和head和kblian
        • (1).启动EslaticSearch (9200)
        • (2).启动Es-head (9101)
        • (3).启动 Kibana (5602)
    • 1.项目依赖
    • 2.启动测试
  • (二)、爬虫
    • 1.数据从哪里获取
    • 2.导入爬虫的依赖
    • 3.编写爬虫工具类
        • (1).实体类
        • (2).工具类编写
    • 4.导入配置类
  • (三)、将爬取到的数据存放到ES
    • 1.创建Service层
    • 2.进行测试 (ES是否存放成功)
  • (四)、从ES中分页读取数据 (关键字不能为中文)
    • 1.从ES中读取数据
        • (1).ContentService 层
        • (2).ContentController 控制层
    • 2.错误演示 (读取es中没有的数据)
  • (五)、前后端交互
    • 1.新增两个js
    • 2.修改原本的页面信息
        • (1).修改的前端页面
    • 3.在批量插入数据的时候把id给注释掉
    • 4.运行测试成功
  • (六)、实现搜索的高亮
    • 1.实现搜索高亮
        • (1).ContentService 层
        • (2).ContentController 层
        • (3).我们发现结果没有进行解析
    • 2.解决结果没有解析

(一)、搭建环境

0.启动ElasticSearch和head和kblian

(1).启动EslaticSearch (9200)

在这里插入图片描述

(2).启动Es-head (9101)

在这里插入图片描述

(3).启动 Kibana (5602)

在这里插入图片描述

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.启动测试

在这里插入图片描述

(二)、爬虫

1.数据从哪里获取

  • 数据库获取。
  • 消息队列中获取中。
  • 爬虫

2.导入爬虫的依赖

tika包解析电影的.jsoup解析网页

<!--        jsoup解析网页-->
<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.解析网页 返回的document对象就是浏览器的Document对象
        Document document = Jsoup.parse(new URL(url), 3000);
        // 3.利用js的Document对象进行操作  ->获取商品整个html页面
        Element element = document.getElementById("J_goodsList");
        // 4.获取所有的li元素 是一个集合。
        Elements elements = element.getElementsByTag("li");

        // 创建一个链表,用于存放我们爬取到的信息
        ArrayList<Content> contents = new ArrayList<>();

        // 5.获取元素中的各个内容
        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);
        }
    }
}

在这里插入图片描述

4.导入配置类

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;
    }
}

(三)、将爬取到的数据存放到ES

1.创建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.解析数据放入我们的es索引中
    public Boolean parseContent(String keywords) throws Exception {
        List<Content> list = new HtmlParseUtil().parseJD(keywords);
        // 2. 把查询到的数据批量放入es中去
        BulkRequest bulkRequest = new BulkRequest();
        // 3.设置超时的时间
        bulkRequest.timeout("2s");
        // 4.创建一个新的索引名字叫做 jd_goods ⭐⭐运行第二次的时候,要把创建库的语句给删除掉
        CreateIndexRequest request = new CreateIndexRequest("jd_goods");
        client.indices().create(request, RequestOptions.DEFAULT);
        // 5.批量插入到数据中 并设置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是否存放成功)

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"));
    }

}

在这里插入图片描述

(四)、从ES中分页读取数据 (关键字不能为中文)

切记我们只能读取到我们ES中存放的数据,假如进行查询没有存放在ES的数据,我们就会得到空的数据。

1.从ES中读取数据

(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.解析数据放入我们的es索引中
    public Boolean parseContent(String keywords) throws Exception {
        List<Content> list = new HtmlParseUtil().parseJD(keywords);
        // 2. 把查询到的数据批量放入es中去
        BulkRequest bulkRequest = new BulkRequest();
        // 3.设置超时的时间
        bulkRequest.timeout("2s");
        // 4.创建一个新的索引名字叫做 jd_goods
//        CreateIndexRequest request = new CreateIndexRequest("jd_goods");
//        client.indices().create(request, RequestOptions.DEFAULT);
        // 5.批量插入到数据中 并设置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中进行搜索内容
    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.构建搜索条件  ⭐⭐
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

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

        // 4. 精确匹配: 第一个参数是参数列名,第二个参数是 搜索的内容 ⭐⭐⭐⭐
        TermQueryBuilder query = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 5.执行搜索 ⭐⭐⭐⭐⭐
        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT); //这里会得到一个结果

        // 6.解析结果  ⭐⭐⭐⭐⭐⭐
        SearchHits hits = searchResponse.getHits(); // 这里会获取到一个对象,对象里面包含着一个hits数组
        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;

    // 普通查询数据
    @GetMapping("/parse/{keywords}")
    public Boolean parse(@PathVariable("keywords") String keywords) throws Exception {
        return contentService.parseContent(keywords);
    }

    // 分页查询数据加高亮
    @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);
    }

    //


}

在这里插入图片描述

2.错误演示 (读取es中没有的数据)

1. 我们在ES中存放的关键字是 java 而我们读取的关键字是 夏装
在这里插入图片描述
2. 读取不到夏装的数据
在这里插入图片描述

(五)、前后端交互

1.新增两个js

在这里插入图片描述

2.修改原本的页面信息

(1).修改的前端页面

index.html

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

<head>
    <meta charset="utf-8"/>
    <title>狂神说Java-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="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>狂神说大数据</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>

                <!-- 排序规则 -->
                <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>
                            <!--标题-->
                            <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: '', //搜索的关键字
            results:[] //搜索的结果
        },
        methods: {
            searchKey() {
                var keyword = this.keywords;
                console.log(keyword);
                //对接后端的接口,异步获取查询到的值
                axios.get('search/' + keyword + "/1/10").then(response => {
                    console.log(response);
                    this.results = response.data; // 绑定数据
                })
            }
        }
    })
</script>

</body>
</html>

3.在批量插入数据的时候把id给注释掉

在这里插入图片描述

4.运行测试成功

读取的都是es中的数据,假如es中没有数据的话,就会查不到
在这里插入图片描述
在这里插入图片描述

(六)、实现搜索的高亮

1.实现搜索高亮

(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.解析数据放入我们的es索引中
    public Boolean parseContent(String keywords) throws Exception {
        List<Content> list = new HtmlParseUtil().parseJD(keywords);
        // 2. 把查询到的数据批量放入es中去
        BulkRequest bulkRequest = new BulkRequest();
        // 3.设置超时的时间
        bulkRequest.timeout("2s");
        // 4.创建一个新的索引名字叫做 jd_goods
//        CreateIndexRequest request = new CreateIndexRequest("jd_goods");
//        client.indices().create(request, RequestOptions.DEFAULT);
        // 5.批量插入到数据中 并设置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数据实现基本的搜索功能
    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.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

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

        // 4. 精确匹配: 第一个参数是参数列名,第二个参数是 搜索的内容
        TermQueryBuilder query = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 5.执行搜索
        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT); //这里会得到一个结果

        // 6.解析结果
        SearchHits hits = searchResponse.getHits(); // 这里会获取到一个对象,对象里面包含着一个hits数组
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    // 3.获取ES数据实现高亮+分页
    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.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

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


        // 4. 精确匹配: 第一个参数是参数列名,第二个参数是 搜索的内容
        TermQueryBuilder query = QueryBuilders.termQuery("title", keywords);
        searchSourceBuilder.query(query);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        // 5.配置高亮设置 ⭐
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false); //一个文本中多个关键字只高亮一个关键字
        highlightBuilder.field("title"); //对那个属性进行高亮
        highlightBuilder.preTags("<span style='color:yellow'>"); //文本的前标签
        highlightBuilder.postTags("</span>"); // 文本的后标签
        // 6.执行高亮设置 ⭐⭐
        searchSourceBuilder.highlighter(highlightBuilder);


        // 7.执行搜索
        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT); //这里会得到一个结果

        // 8.将原本文本解析成高亮文本 ⭐⭐⭐
        SearchHits hits = searchResponse.getHits(); // 这里会获取到一个对象,对象里面包含着一个hits数组
        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();  // 原来的结果
            // 解析高亮的字段,将原来的字段换为我们高亮的字段即可
            if (title!=null){
                Text[] fragments = title.fragments();
                String n_title="";
                for (Text text : fragments) {
                    n_title+=text;
                }
                sourceAsMap.put("title",n_title);  //高亮字段替换掉原来的内容即可。
            }
            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;

    // 普通查询数据
    @GetMapping("/parse/{keywords}")
    public Boolean parse(@PathVariable("keywords") String keywords) throws Exception {
        return contentService.parseContent(keywords);
    }

    // 分页查询数据加高亮
    @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).我们发现结果没有进行解析

在这里插入图片描述

2.解决结果没有解析

vue 页面没有被html解析,我们只需要html解析即可
在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/704488.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Selenium系列(四) - 详细解读鼠标操作

引入HTML页面 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>测试笔记</title> </head> <body><a>用户名:</a> <input id"username" class"userna…

航空枢纽联通亚欧,开放合作互利共赢 —乌鲁木齐国际航空枢纽建设论坛将于7月6日召开

为创新开放型经济体制&#xff0c;加快建设对外开放大通道&#xff0c;更好利用国际国内两个市场、两种资源&#xff0c;积极服务和融入双循环新发展格局&#xff0c;促进经济高质量发展&#xff0c;2023年7月6日-7日&#xff0c;以“航空枢纽联通亚欧&#xff0c;开放合作互利…

基于matlab使用单眼摄像机图像数据构建室内环境地图并估计摄像机的轨迹(附源码)

一、前言 视觉同步定位和映射 &#xff08;vSLAM&#xff09; 是指计算摄像机相对于周围环境的位置和方向&#xff0c;同时映射环境的过程。该过程仅使用来自相机的视觉输入。vSLAM 的应用包括增强现实、机器人和自动驾驶。 此示例演示如何处理来自单眼摄像机的图像数据&…

从小白到大神之路之学习运维第50天---第三阶段----MMM高可用集群数据库的安装部署

第三阶段基础 时 间&#xff1a;2023年6月30日 参加人&#xff1a;全班人员 内 容&#xff1a; Mysql---MMM高可用集群架构 目录 一、MMM介绍 二、MMM工作原理 三、MMM安装部署 环境配置&#xff1a;&#xff08;所有主机配置&#xff09; 1、主机信息 ​编辑 2、…

探索无限可能的教育新领域,景联文教育GPT题库开启智慧教育新时代!

随着人工智能技术的快速发展&#xff0c;教育领域也将迎来一场革命性的变革。景联文科技是AI基础数据行业的头部企业&#xff0c;近期推出了一款高质量教育GPT题库。 景联文科技高质量教育GPT题库采用了先进的自然语言处理技术和深度学习算法&#xff0c;可以实现对各类题目的智…

一个输入网址就可显示网站安全性及网站主要内容的含GUI的Python小程序

文章目录 1.一些杂七杂八的引入2.实现2.1 显示网站安全性2.2 安装所需python包2.2.1 requests包2.2.1 beautifulsoup包 3.源码展示4.效果展示 1.一些杂七杂八的引入 上次发了一个类似爬虫&#xff0c;可以自动下载网页图片的python小程序&#xff08;详见一个自动下载网页图片…

【Web工具】3D 旋转中各数据格式之间的转换

1 Rotation Master — Link GitHub: Link 2 3D Rotation Converter — Link GitHub: Link 3 Quaternions — Link 4 Rotation Conversion Tool — Link 这是个人博客网站&#xff0c;其中可能有你需要的知识: Link

Prometheus实现自定义指标监控

1、Prometheus实现自定义指标监控 前面我们已经通过 PrometheusGrafana 实现了监控&#xff0c;可以在 Grafana 上看到对应的 SpringBoot 应用信息了&#xff0c; 通过这些信息我们可以对 SpringBoot 应用有更全面的监控。 但是如果我们需要对一些业务指标做监控&#xff0c;…

老文章可以删了!!!。2023年最新IDEA中 Java程序 | Java+Kotlin混合开发的程序如何打包成jar包和exe文件(gradle版本)

文章内容&#xff1a; 一. JAVA | JAVA和Kotlin混开开发的程序打包成jar方法 1.1 方法一 &#xff1a;IDEA中手动打包 1.2 方法二 &#xff1a;build.gradle中配置后编译时打包 二. JAVA | JAVA和Kotlin混合开发的程序打包成exe的方法 一. JAVA | JAVA和Kotlin混开开发的程序…

使用 Jetpack Compose 实现 ViewPager2

在此博客中&#xff0c;我们将介绍如何在Jetpack Compose中实现ViewPager2的功能。我们将使用Accompanist库中的Pager库&#xff0c;这是由Google开发的一个用于Jetpack Compose的库。 首先&#xff0c;需要将Pager库添加到你的项目中&#xff1a; implementation androidx.co…

投票活动链接制作方法网络投票办法公众号做投票链接

用户在使用微信投票的时候&#xff0c;需要功能齐全&#xff0c;又快捷方便的投票小程序。 而“活动星投票”这款软件使用非常的方便&#xff0c;用户可以随时使用手机微信小程序获得线上投票服务&#xff0c;很多用户都很喜欢“活动星投票”这款软件。 “活动星投票”小程序在…

ModelScope魔搭社区AI模型下载数据可能存在严重造假问题

目录 摘要&#xff1a; 一、数据分析 二、可能存在的问题 三、结论与建议 摘要&#xff1a; ModelScope魔搭社区作为一个AI模型共享平台&#xff0c;旨在提供各种领域的模型供用户下载和使用。然而&#xff0c;通过对其提供的数据进行分析&#xff0c;发现其中存在一定的数…

【Flutter】built_value 解决 Flutter 中的不可变性问题

文章目录 一、 前言二、 什么是 built_value&#xff1f;三、 为什么我们需要 built_value&#xff1f;四、 如何在 Flutter 中安装和设置 built_value&#xff1f;五、 如何使用 built_value 创建不可变的值类型&#xff1f;六、 如何使用 built_value 创建枚举类&#xff1f;…

pcl基于八叉树进行空间划分和搜索操作

建立空间索引在点云数据处理中已被广泛应用&#xff0c;常见空间索引一般是自顶向下逐级划分空间的各种空间索引结构&#xff0c;比较有代表性的包括 BSP 树、KD 树、KDB 树、 R树、R树、CELL 树、四叉树和八叉树等索引结构&#xff0c;而在这些结构中 KD 树和八叉树在 3D点云数…

使用键鼠网络共享用windows控制ubuntu,实现跨屏跨系统操作

经调研发现几种网络共享鼠标方案&#xff1a;sharemouse、synergy以及Barrier&#xff0c;由于没找到合适的资料去配置sharemouse&#xff0c;synergy又收费&#xff0c;所以使用Barrier。 一、Ubuntu安装Barrier 到Ubuntu软件商城搜索Barrier点击安装即可&#xff0c;这就不再…

学成在线----day8

1、课程发布 为了提高网站的速度需要将课程信息进行缓存&#xff0c;并且要将课程信息加入索引库方便搜索&#xff0c;下图显示了课程发布后课程信息的流转情况&#xff1a; 1、向内容管理数据库的课程发布表存储课程发布信息&#xff0c;更新课程基本信息表中发布状态为已发…

【Shell】读取用户终端输入内容

授权 cd /Users/lion/Downloads/shell-test-demos chmod ux *.shread_user_enter.sh #!/bin/bashprintHelp() {echo "1. hello"echo "2. world"echo "0. exit" }printHelpnumber"" while [ -z $number ]; doread -p "enter a n…

干货,让微信群活跃的秘籍

微信用户数量庞大、使用率高&#xff0c;是很多企业/商家做社群营销的第一平台&#xff0c;所以目前有很多微信社群营销管理系统。我一直在用的一个多群管理工具---微信管理系统&#xff0c;对于新手来说&#xff0c;操作也是十分的简单易上手&#xff0c;每一步都有教程指导&a…

网站被黑挂马应该怎么解决

遇到网站被黑或者被挂马&#xff0c;其实都是很正常的现象&#xff0c;做网站的站长&#xff0c;几乎都有网站被黑的历史 遇到这种问题&#xff0c;首先&#xff1a; 检查网站源文件的日期&#xff0c;回顾一下在过去一段时间里面&#xff0c;你有没有对源文件做过改动&#x…

程序员性能之道,从使用perf开始!

一、perf简介 从2.6.31内核开始&#xff0c;Linux内核自带了一个性能分析工具perf&#xff0c;能够进行函数级与指令级的热点查找。通过它&#xff0c;应用程序可以利用 PMU&#xff0c;tracepoint 和内核中的特殊计数器来进行性能统计。它不但可以分析指定应用程序的性能问题…