ElasticSearch集成SpringBoot+实战


上一篇学习 笔记: ElasticSearch核心概念与REST风格说明

SpringBoot和es相关操作

es集成SpringBoot

查看官方文档
1、es客户端
请添加图片描述
2、es客户端的类别和版本,使用7.14版本,因为这里使用的 是java高级客户端,但是7.15不推荐java高级客户端,使用的是客户端
请添加图片描述
3、使用Java REST Client [7.14]的Java High Level REST Client
请添加图片描述
4、根据官方文档学习
请添加图片描述

  • 找到Java High Level REST Client 原生依赖
    请添加图片描述
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.14.2</version>
</dependency>
  • 找对象 RestHighLevelClient
    请添加图片描述

5、开始集成springboot

  • 创建一个空项目
    请添加图片描述
    请添加图片描述
  • 空项目建立完成之后,在这个空项目上增加一个springboot模块,并添加依赖,并为项目配置jdk1.8
    请添加图片描述请添加图片描述
    请添加图片描述
    请添加图片描述
  • 检查项目的jdk和js(确保 jdk一定在 1.8以上)
    请添加图片描述
    请添加图片描述
  • 检查项目导入的 es版本要和本地es版本一致,我本地用的是7.6.1
    请添加图片描述请添加图片描述
    请添加图片描述
  • 编写es配置类,绑定本地而是客户端,并且将RestHighLevelClient注入到spring容器中,让容器接管,到这一步,springboot和es集成已经完成,接下来可以通过高级客户端进行操作操作了
package com.wangjiale.springboot_es_api.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 wangjiale
 * @description: ElasticsearchConfig
 * @create 2021-10-06 21:28
 */
@Configuration
public class ElasticsearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}

请添加图片描述
本地 是127.0.0.1:9200
请添加图片描述

使用springboot操作es API

索引相关

1、创建索引

package com.wangjiale.springboot_es_api;

import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class SpringbootEsApiApplicationTests {

    @Autowired
    public RestHighLevelClient restHighLevelClient;
    
    //测试索引请求request
    @Test
    public void test1() throws IOException {
        //创建索引请求
        CreateIndexRequest indexRequest = new CreateIndexRequest("wangjiale_index");

        //创建索引客户端
        IndicesClient indices = restHighLevelClient.indices();
        //索引客户端执行索引请求 IndicesClient
        CreateIndexResponse indexResponse = indices.create(indexRequest,
                RequestOptions.DEFAULT);//RequestOptions.DEFAULT 默认请求参数

        System.out.println(indexResponse);

    }

}

请添加图片描述
请添加图片描述
2、获得索引,判断索引是否存在

 @Test
     void test2() throws IOException{
        //获取索引请求
        GetIndexRequest index = new GetIndexRequest("wangjiale_index");
        //通过高级客户端创建索引客户端
        IndicesClient indices = restHighLevelClient.indices();
        //索引客户端发出索引是否存在
        boolean exists = indices.exists(index, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

请添加图片描述
3、删除索引

  @Test
    public void test3() throws IOException {
        //创建删除索引的请求
        DeleteIndexRequest index = new DeleteIndexRequest("wangjiale_index");
        //通过高级客户端创建索引客户端
        IndicesClient indices = restHighLevelClient.indices();
        //索引客端端 删除索引  AcknowledgedResponse 确认响应
        AcknowledgedResponse delete = indices.delete(index, RequestOptions.DEFAULT);

        //输出是否删除
        System.out.println(delete.isAcknowledged());

    }

请添加图片描述
请添加图片描述

文档相关

使用文档时需要在有索引的基础上,在此之间建立索引“wangjiale_index”

1、创建测试文档;

   // 创建文档  规则 put /wangjiale_index/_doc/doc_1
    @Test
    public void test4() throws IOException {
        //获得索引
        IndexRequest index = new IndexRequest("wangjiale_index");
        User user1 = new User().setName("王五")
                .setPassword("123456")
                .setSex('男')
                .setAge(3);

        //设置文档id,也相当于是文档的标识 , index.id()如果不写参数就会默认生成
        index.id("doc_1");
        //设置请求时间
        index.timeout(TimeValue.timeValueDays(1));
        // 将我们的数据放入请求 json
        index.source(JSON.toJSONString(user1), XContentType.JSON);
        // 客户端发送请求,获取响应结果
        IndexResponse indexResponse = restHighLevelClient.index(index, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
        System.out.println(indexResponse.status());

    }

请添加图片描述
请添加图片描述
2、判断文档是否存在,存在 的话不打印_source信息

 // 获取文档,判断是否存在 get /wangjiale_index/_doc/doc_1
    @Test
    public void test5() throws IOException {
        //获得get请求 获取索引wangjiale_index 中doc_1 的内容
        GetRequest getRequest = new GetRequest("wangjiale_index", "doc_1");
        //这里不打印_source中的内容 ,因为这里主要判断文档是否存在
        getRequest.fetchSourceContext(new FetchSourceContext(false));

        getRequest.storedFields("_none_");
        //判断该文档是否存在
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);

        System.out.println(exists);

    }

请添加图片描述

3、获取文档信息

    //  获取文档信息 get wangjiale_index/_doc/doc_1
    @Test
    public void test6() throws IOException {
        //使用get 获取索引wangjiale_index 中doc_1 的内容
        GetRequest getRequest = new GetRequest("wangjiale_index", "doc_1");
        //发送get请求
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields);//相当于documentFields.toString()
        System.out.println(documentFields.toString());
        // 返回的全部内容和命令是一样的 
    }

请添加图片描述
4、更新文档

 //更新文档
    @Test
    public void test7() throws IOException {
        //创建更新请求
        UpdateRequest updateRequest = new UpdateRequest("wangjiale_index", "doc_1");
        //设置更新超时时间
        updateRequest.timeout("1s");
        //数据更新
        User user1 = new User().setName("王五更新")
                .setAge(13);
        //更新请求文档
        updateRequest.doc(JSON.toJSONString(user1), XContentType.JSON);
        //高级客户端发送更新请求
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        //更新状态是否成功
        System.out.println(updateResponse.status());


    }

请添加图片描述
请添加图片描述
5、删除文档


    // 删除文档记录
    @Test
    public void test8() throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest("wangjiale_index", "doc_1");

        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);

        System.out.println(delete.status());

    }

请添加图片描述
请添加图片描述
6、批量插入

    @Test
    public void test9() throws IOException {
        //设置批量请求
        BulkRequest bulkRequest = new BulkRequest();
        //设置时间
        bulkRequest.timeout("10s");
        ArrayList<User> users = new ArrayList<>();
        users.add(new User().setName("张三1")
                .setPassword("123456")
                .setSex('男')
                .setAge(3));
        users.add(new User().setName("张三2")
                .setPassword("123456")
                .setSex('女')
                .setAge(13));
        users.add(new User().setName("李四")
                .setPassword("123456")
                .setSex('男')
                .setAge(39));
        users.add(new User().setName("王五")
                .setPassword("123456")
                .setSex('男')
                .setAge(74));

        for (int i = 0; i < users.size(); i++) {
            //批量增加
            bulkRequest.add(new IndexRequest("wangjiale_index")//索引请求
                    .id("doc_"+(i+1))//文档id
                    .source(JSON.toJSONString(users.get(i)),XContentType.JSON));//文档数据
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);//客户端发送批量请求

        System.out.println(bulkResponse.hasFailures());//判断是否批量请求是否失败

    }

请添加图片描述
请添加图片描述
7、批量更新

  @Test
    public void test9() throws IOException {
        //设置批量请求
        BulkRequest bulkRequest = new BulkRequest();
        //设置时间
        bulkRequest.timeout("10s");
        ArrayList<User> users = new ArrayList<>();
        users.add(new User().setName("张三1更新")
                .setPassword("123456")
                .setSex('男')
                .setAge(3));
        users.add(new User().setName("张三e更新")
                .setPassword("123456")
                .setSex('女')
                .setAge(13));
        users.add(new User().setName("李四更新")
                .setPassword("123456")
                .setSex('男')
                .setAge(39));
        users.add(new User().setName("王五更新")
                .setPassword("123456")
                .setSex('男')
                .setAge(74));

        for (int i = 0; i < users.size(); i++) {

          bulkRequest.add(new UpdateRequest("wangjiale_index", "doc_"+(i+1))
          .doc(JSON.toJSONString(users.get(i)),XContentType.JSON));

        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);//客户端发送批量请求

        System.out.println(bulkResponse.hasFailures());//判断是否批量请求是否失败

    }

请添加图片描述

8、批量删除

  @Test
    public void test9() throws IOException {
        //设置批量请求
        BulkRequest bulkRequest = new BulkRequest();
        //设置时间
        bulkRequest.timeout("10s");
        for (int i = 0; i < 4; i++) {
            bulkRequest.add(new DeleteRequest("wangjiale_index", "doc_"+(i+1)));
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);//客户端发送批量请求
        System.out.println(bulkResponse.hasFailures());//判断是否批量请求是否失败
    }

请添加图片描述
9、复杂搜索
数据准备

在这里插入图片描述

  // 查询
    // SearchRequest 搜索请求
    // SearchSourceBuilder 条件构造
    // HighLightBuilder 构建高亮
    // TermQueryBuilder  精确查询
    // MatchAllQueryBuilder
    // xxx QueryBuilder 对应我们刚才看到的命令!
    @Test
    public void test10() throws IOException {
        //创建搜索请求
        SearchRequest searchRequest = new SearchRequest("wangjiale_index");
        //构建搜索条件 SearchSourceBuilder 我们要的数据都在_source中
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //创建查询条件,我们使用工具类QueryBuilders
        //bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //“or”查询
        boolQuery.should(QueryBuilders.matchQuery("name","张三"));
        boolQuery.should(QueryBuilders.matchQuery("age",74));
        //分页
        sourceBuilder.from(0);
        sourceBuilder.size(10);
        //将查询条件放入搜索构建器中
        sourceBuilder.query(boolQuery);
        //设置查询时间
        sourceBuilder.timeout(new TimeValue(60));
        //把搜索构建器放入搜索请求中
        SearchRequest source = searchRequest.source(sourceBuilder);
        SearchResponse search = restHighLevelClient.search(source, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit documentFields : hits1) {
            System.out.println(documentFields);
        } }

结果

{
  "_index" : "wangjiale_index",
  "_type" : "_doc",
  "_id" : "doc_2",
  "_score" : 1.4523083,
  "_source" : {
    "age" : 13,
    "name" : "张三",
    "password" : "123456",
    "sex" : "女"
  }
}
{
  "_index" : "wangjiale_index",
  "_type" : "_doc",
  "_id" : "doc_1",
  "_score" : 1.2199391,
  "_source" : {
    "age" : 3,
    "name" : "张三1",
    "password" : "123456",
    "sex" : "男"
  }
}
{
  "_index" : "wangjiale_index",
  "_type" : "_doc",
  "_id" : "doc_4",
  "_score" : 1.0,
  "_source" : {
    "age" : 74,
    "name" : "王五",
    "password" : "123456",
    "sex" : "男"
  }
}

ES实战

静态页面资源提取
链接:链接:https://pan.baidu.com/s/1NxOfgXPOs75Zcn51bc-YLw
提取码:nku8

1、创建项目,步骤如下
请添加图片描述
请添加图片描述
在这里插入图片描述
2、把准备的静态资源放入项目中
请添加图片描述
请添加图片描述
测试将静态资源放入项目中是否成功
在这里插入图片描述

数据准备,静态页面解析

数据问题?数据库获取,消息队列中获取,都可以成为数据源,爬虫!
爬取数据:(获取请求返回的页面信息,筛选出我们想要的数据就可以了!)
导入jsoup包

<!--        解析网页jsoup-->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>

编写工具包,并测试 是否可以拿到京东静态页面数据

    public static void main(String[] args) throws Exception {
        //获取请求 keyword参数是关键字搜索
        String url ="https://search.jd.com/Search?keyword=nars";

        //使用Jsoup.parse 解析请求,第一个参数是url请求,第二个参数是超时时间
        // 解析网页。(Jsoup 返回Document就是Document对象)
        Document parse = Jsoup.parse(new URL(url), 300000);

        //此时已经获得请求返回也页面的Document对象
        //通过Document对象获取div(J_goodsList),搜索商品列表
        Element j_goodsList = parse.getElementById("J_goodsList");
        //获得div中的所有列表
        Elements lis = j_goodsList.getElementsByTag("li");
        //遍历列表,并取出里面的数据
        for (Element li : lis) {
            // 因为京东是延时加载 所以要加载图片是data-lazy-img
            String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img");// 获取li下第一张图片
           //获得价格div
            String price = li.getElementsByClass("p-price").eq(0).text();

            //获得名字div
            String name = li.getElementsByClass("p-name").eq(0).text();

            System.out.println("图片:"+img);
            System.out.println("价格:"+price);
            System.out.println("name:"+name);
        }
    }

把工具包封装成一个方法

public class HtmlParseUtil {

    public static List<Jd_Content> parseJD(String keywords) throws Exception {
        List<Jd_Content> list = new ArrayList<>();
        String url ="https://search.jd.com/Search?keyword="+keywords;
        Document parse = Jsoup.parse(new URL(url), 300000);
        Element j_goodsList = parse.getElementById("J_goodsList");
        Elements lis = j_goodsList.getElementsByTag("li");
        for (Element li : lis) {
            // 因为京东是延时加载 所以要加载图片是data-lazy-img
            String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img");// 获取li下第一张图片
            //获得价格div
            String price = li.getElementsByClass("p-price").eq(0).text();

            //获得名字div
            String name = li.getElementsByClass("p-name").eq(0).text();
            Jd_Content jd_content = new Jd_Content();
            jd_content.setImg(img).setPrice(price).setName(name);

            list.add(jd_content);
        }
        return list;
    }
}

项目搭建,代码实现

此时项目结构如下图
在这里插入图片描述
在这里插入图片描述

项目中所有的依赖

<?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.wangjiale</groupId>
    <artifactId>jd-springboot-es</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jd-springboot-es</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <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>
        <!--        解析网页jsoup-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.13.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</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>

实体类:
1、Indexes (es中的索引名字)

package com.wangjiale.jd_springboot_es.entity;


/**
 * @author wangjiale
 * @description: Indexes
 * @create 2021-10-13 16:41
 */
public class Indexes {
    public static String NAME ="jd_index";

}

2、Jd_Content (京东商品信息)

package com.wangjiale.jd_springboot_es.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @author wangjiale
 * @description: Jd_Content
 * @create 2021-10-13 15:54
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Jd_Content {
    private String img;
    private String price;
    private String name;
}

配置文件:

package com.wangjiale.jd_springboot_es.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 wangjiale
 * @description: ElasticsearchConfig
 * @create 2021-10-13 16:56
 */
@Configuration
public class ElasticsearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}

业务逻辑:
1、EsService

package com.wangjiale.jd_springboot_es.service;


import com.wangjiale.jd_springboot_es.entity.Jd_Content;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author wangjiale
 * @description: EsService
 * @create 2021-10-13 16:07
 */

public interface EsService {
    public Boolean parseContent(String keywords) throws Exception;
    public List<Map<String,Object>> secher(String keywords, int pageNo, int pageSize) throws IOException;
}

2、EsServiceImp

package com.wangjiale.jd_springboot_es.service.impl;

import com.alibaba.fastjson.JSON;
import com.wangjiale.jd_springboot_es.entity.Indexes;
import com.wangjiale.jd_springboot_es.entity.Jd_Content;
import com.wangjiale.jd_springboot_es.service.EsService;
import com.wangjiale.jd_springboot_es.util.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.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
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;

/**
 * @author wangjiale
 * @description: EsServiceImp
 * @create 2021-10-13 16:09
 */
@Service
public class EsServiceImp implements EsService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 1、解析数据放入 es 索引中
     */
    public Boolean parseContent(String keywords) throws Exception {
        List<Jd_Content> jd_contents = HtmlParseUtil.parseJD(keywords);

        BulkRequest bulkRequest = new BulkRequest();

        bulkRequest.timeout("2m");

        for (Jd_Content jd_content : jd_contents) {
            bulkRequest.add(
                    new IndexRequest(Indexes.NAME).
                    source(JSON.toJSONString(jd_content),XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    @Override
    public List<Map<String,Object>> secher(String keywords, int pageNo, int pageSize) throws IOException {
        if (pageNo <=1){
            pageNo =1;
        }
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        //创建搜索请求
        SearchRequest searchRequest = new SearchRequest(Indexes.NAME);
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.query(new MatchQueryBuilder("name",keywords));

        sourceBuilder.timeout(new TimeValue(10000));

        //设置分页

        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //把搜索条件放入搜索请求
        searchRequest.source(sourceBuilder);

        //执行搜索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();

        for (SearchHit hit : hits) {
            maps.add(hit.getSourceAsMap());
        }
        return maps;


    }
}

控制器:

package com.wangjiale.jd_springboot_es.controller;

import com.wangjiale.jd_springboot_es.entity.Jd_Content;
import com.wangjiale.jd_springboot_es.service.EsService;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author wangjiale
 * @description: EsController
 * @create 2021-10-13 18:35
 */
@RestController
public class EsController {
    @Autowired
    public EsService esService;

    @GetMapping("/parse/{keysword}")
    public Boolean parse(@PathVariable("keysword") String keysword) throws Exception {
        return esService.parseContent(keysword);
    }

    @GetMapping("/search/{keywords}/{pageNo}/{pageSize}")
    public List<Map<String,Object>> search(@PathVariable("keywords") String keywords,
                                           @PathVariable("pageNo")int pageNo,
                                           @PathVariable("pageSize")int pageSize) throws IOException {
        List<Map<String, Object>> secher = esService.secher(keywords, pageNo, pageSize);

        return secher;

    }

}

页面显示 :使用Vue做前后端分离

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

<head>
    <meta charset="utf-8"/>
    <title>王家乐-仿京东实战</title>
    <link rel="stylesheet" th:href="@{/css/style.css}"/>
 <!--使用Vue做前后端分离-->
    <script th:src="@{/js/axios.min.js}"></script>
    <script th:src="@{/js/vue.min.js}"></script>
</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">
                                                <!--v-model="keyword" 和 Vue 双向绑定-->
                                                <input v-model="keyword" type="text" autocomplete="off" value="dd" id="mq"
                                                       class="s-combobox-input" aria-haspopup="true">
                                            </div>
                                        </div>
                                        <button type="submit" id="searchbtn" @click.prevent="searchKey" >搜索</button>
                                    </div>
                                </fieldset>
                            </form>
                            <ul class="relKeyTop">
                                <li><a>6666666</a></li>
                                <li><a>7777777</a></li>
                                <li><a>8888888</a></li>
                                <li><a>9999999</a></li>
                                <li><a>1111111</a></li>
                                <li><a>2222222</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>{{result.price}}</em>
                            </p>
                            <!--标题-->
                            <p class="productTitle">
                                <a> {{result.name}} </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>

<script>
    //创建Vue对象
new Vue({
    el: '#app',//绑定数据
    data : {
        keyword: '',//搜索的关键字
        results : []//搜索的结果
    },
    methods : {
      searchKey(){
         var keyword = this.keyword;
         // console.log(keyword);
          //对接后端接口
          axios.get("search/"+keyword+"/1/15").then(response =>{
              console.log(response.data);
              this.results = response.data;//绑定数据
          })
    }
    }
})
</script>

</body>
</html>

启动类:

package com.wangjiale.jd_springboot_es;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JdSpringbootEsApplication {

    public static void main(String[] args) {
        SpringApplication.run(JdSpringbootEsApplication.class, args);
    }

}

最终效果图:在这里插入图片描述

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值