• Java项目(二)--Springboot + ElasticSearch 构建博客检索系统(4)- SpringBoot集成ES


    SpringBoot集成ES

    Springboot项目搭建

    打开IDEA,点击New Project新建项目,点击Spring Initializr配置如下,点击Next。
    在这里插入图片描述
    然后在New Project界面配置如下,然后点击Finish。
    在这里插入图片描述
    在这里插入图片描述
    注意生成项目的Springboot版本为2.7.4,为了避免本教程的配置过时报错,我们把Springboot版本改为2.2.0.RELEASE。
    在这里插入图片描述
    打开src/main/resources/application.properties添加配置信息为

    # 通用数据源配置
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/es-db?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    spring.datasource.username=root
    spring.datasource.password=root
    # Hikari
    spring.datasource.hikari.maximum-pool-size=20
    spring.datasource.hikari.minimum-idle=5
    # JPA 相关配置
    spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
    
    # es 配置
    spring.data.elasticsearch.cluster-nodes: localhost:9300
    spring.data.elasticsearch.cluster-name: elasticsearch
    
    # mvc
    spring.mvc.static-path-pattern=/**
    
    spring.devtools.livereload.enabled=true
    spring.devtools.restart.additional-paths=static/**
    
    # 日期格式化4
    spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    启动项目成功。
    在这里插入图片描述

    项目结构和JPA演示

    首先在com.ql.springboot.es.entity.mysql包下创建MysqlBlog.java实体类。

    package com.ql.springboot.es.entity.mysql;
    
    import lombok.Data;
    
    import javax.persistence.*;
    import java.util.Date;
    
    @Data
    @Table(name="t_blog")
    @Entity
    public class MysqlBlog {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
        private String title;
        private String author;
        @Column(columnDefinition = "mediumtext")
        private String content;
        private Date createTime;
        private Date updateTime;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    然后在com.ql.springboot.es.repository.mysql包下创建MysqlBlogRepository.java接口

    package com.ql.springboot.es.repository.mysql;
    
    import com.ql.springboot.es.entity.mysql.MysqlBlog;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface MysqlBlogRepository extends JpaRepository<MysqlBlog,Integer> {
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    然后在com.ql.springboot.es.controller包下创建IndexController.java

    package com.ql.springboot.es.controller;
    
    import com.ql.springboot.es.entity.mysql.MysqlBlog;
    import com.ql.springboot.es.repository.mysql.MysqlBlogRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    @Controller
    public class IndexController {
        @Autowired
        private MysqlBlogRepository mysqlBlogRepository;
    
        @RequestMapping("/")
        public String index(){
            List<MysqlBlog> all = mysqlBlogRepository.findAll();
            System.out.println(all.size());
            return "index.html";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    在src/main/resources/static目录下创建index.html

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Springboot + es 构建博客检索系统title>
    head>
    <body>
    hello world
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    启动项目在浏览器里访问http://localhost:8080/,控制台也打出了查出的数据行数。
    在这里插入图片描述

    Springboot集成ES

    首先在pom.xml中添加ES依赖

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-elasticsearchartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    然后在com.ql.springboot.es.entity.es包下创建EsBlog.java实体类

    package com.ql.springboot.es.entity.es;
    
    import lombok.Data;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.elasticsearch.annotations.DateFormat;
    import org.springframework.data.elasticsearch.annotations.Document;
    import org.springframework.data.elasticsearch.annotations.Field;
    import org.springframework.data.elasticsearch.annotations.FieldType;
    
    import javax.persistence.*;
    import java.util.Date;
    
    @Data
    @Document(indexName = "blog", type="doc", useServerConfiguration = true,createIndex = false)
    public class EsBlog {
        @Id
        private Integer id;
        @Field(type = FieldType.Text, analyzer = "ik_max_word")
        private String title;
        @Field(type = FieldType.Text, analyzer = "ik_max_word")
        private String author;
        @Field(type = FieldType.Text, analyzer = "ik_max_word")
        private String content;
        @Field(type = FieldType.Date, format = DateFormat.custom,
            pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
        private Date createTime;
        @Field(type = FieldType.Date, format = DateFormat.custom,
                pattern = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
        private Date updateTime;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    当我们的springboot项目启动的时候,它发现已经引入了es依赖了之后,会检查所有Document实体,如果没有配useServerConfiguration,接下来代码层面的配置都会同步到es的集群当中。而没有配createIndex的话,它会去es里面检查如果已经有blog索引,会把现有的索引删除掉,然后重新创建blog索引。
    但是在实际的开发过程中,我们都是预先的在ES里面数据同步、创建索引、type、及映射等,所以不希望程序员由于手误或其他操作把线上的配置改变掉。所以默认会加useServerConfiguration = true(默认使用线上es的配置)、createIndex = false(不要在springboot项目启动的时候重新创建索引)两个配置。

    然后在com.ql.springboot.es.repository.es包下创建EsBlogRepository.java类

    package com.ql.springboot.es.repository.es;
    
    import com.ql.springboot.es.entity.es.EsBlog;
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    
    public interface EsBlogRepository extends ElasticsearchRepository<EsBlog,Integer> {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    编写测试用例src/test/java/com/ql/springboot/es/SpringbootEsApplicationTests.java并运行。

    package com.ql.springboot.es;
    
    import com.ql.springboot.es.entity.es.EsBlog;
    import com.ql.springboot.es.repository.es.EsBlogRepository;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import java.util.Iterator;
    
    @SpringBootTest
    class SpringbootEsApplicationTests {
    
    	@Autowired
    	EsBlogRepository esBlogRepository;
    
    	@Test
    	void contextLoads() {
    	}
    
    	@Test
    	public void testEs(){
    		Iterable<EsBlog> all = esBlogRepository.findAll();
    		Iterator<EsBlog> iterator = all.iterator();
    		EsBlog next = iterator.next();
    		System.out.println("------------"+next.getTitle());
    	}
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    运行成功。
    在这里插入图片描述

    项目后端REST API 实现

    打开com/ql/springboot/es/repository/mysql/MysqlBlogRepository.java编写查询全部和按关键字查询的方法。

    package com.ql.springboot.es.repository.mysql;
    
    import com.ql.springboot.es.entity.mysql.MysqlBlog;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.query.Param;
    
    import java.util.List;
    
    public interface MysqlBlogRepository extends JpaRepository<MysqlBlog,Integer> {
        @Query("select e from MysqlBlog e order by e.createTime desc ")
        List<MysqlBlog> queryAll();
    
        @Query("select e from MysqlBlog e where e.title like concat('%',:keyword,'%')"
                +" or e.content like concat('%',:keyword,'%') ")
        List<MysqlBlog> queryBlogs(@Param("keyword") String keyword);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    然后在com.ql.springboot.es.controller包下创建DataController.java实现API

    package com.ql.springboot.es.controller;
    
    import com.ql.springboot.es.entity.es.EsBlog;
    import com.ql.springboot.es.entity.mysql.MysqlBlog;
    import com.ql.springboot.es.repository.es.EsBlogRepository;
    import com.ql.springboot.es.repository.mysql.MysqlBlogRepository;
    import lombok.Data;
    import org.elasticsearch.index.query.BoolQueryBuilder;
    import org.elasticsearch.index.query.QueryBuilder;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.util.StopWatch;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.HashMap;
    import java.util.List;
    
    @RestController
    public class DataController {
        @Autowired
        MysqlBlogRepository mysqlBlogRepository;
        @Autowired
        EsBlogRepository esBlogRepository;
    
        @GetMapping("/blogs")
        public Object blog(){
            List<MysqlBlog> mysqlBlogs = mysqlBlogRepository.queryAll();
            return mysqlBlogs;
        }
    
        @PostMapping("/search")
        public Object search(@RequestBody Param param){
            HashMap<String, Object> map = new HashMap<>();
            StopWatch watch = new StopWatch();
            watch.start();
            String type = param.getType();
            if(type.equalsIgnoreCase("mysql")){
                //mysql
                List<MysqlBlog> mysqlBlogs = mysqlBlogRepository.queryBlogs(param.getKeyword());
                map.put("list", mysqlBlogs);
            }else if(type.equalsIgnoreCase("es")){
                //es
                BoolQueryBuilder builder = QueryBuilders.boolQuery();
                builder.should(QueryBuilders.matchPhraseQuery("title",param.getKeyword()));
                builder.should(QueryBuilders.matchPhraseQuery("content",param.getKeyword()));
                String s = builder.toString();
                System.out.println(s);
                Page<EsBlog> search = (Page<EsBlog>) esBlogRepository.search(builder);
                List<EsBlog> content = search.getContent();
                map.put("list", content);
            }else{
                return "i don't understand";
            }
            watch.stop();
            long totalTimeMillis = watch.getTotalTimeMillis();
            map.put("duration", totalTimeMillis);
            return map;
        }
    
        @GetMapping("/blog/{id}")
        public Object blog(@PathVariable("id") Integer id){
            Optional<MysqlBlog> byId = mysqlBlogRepository.findById(id);
            MysqlBlog mysqlBlog = byId.get();
            return mysqlBlog;
        }
    
        @Data
        public static class Param{
            //mysql es
            private String type;
            private String keyword;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    项目前端VUE视图渲染

    在src/main/resources/static/css目录下引入bootstrap样式文件,在src/main/resources/static/js目录下引入VUE相关js文件,在src/main/resources/static/img下引入随机10张图
    在这里插入图片描述

    打开src/main/resources/static/index.html添加页面内容

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-grid.min.css">
        <link rel="stylesheet" href="css/bootstrap-reboot.min.css">
    head>
    <body>
    <div class="container">
        <div class="row" style="margin-top: 20px;">
            <div class="col-12">
                <h2>
                    Springboot + es 构建博客检索系统
                h2>
            div>
        div>
    
        <div class="row" style="margin-top: 20px;" id="app">
            <div class="col-9">
                <form class="form-inline">
                    <div class="form-group mb-2">
                        <input type="text" class="form-control" id="title-mysql" placeholder="检索你的检索" v-model="keyword">
                    div>
                    <button type="button" class="btn btn-primary mb-2" style="margin-left: 5px;" v-on:click="searchWithMysql">mysqlbutton>
                    <button type="button" class="btn btn-primary mb-2" style="margin-left: 5px;" v-on:click="searchWithEs">ESbutton>
                    <span style="margin-left: 10px; color: green;">耗时:{{duration}}span>
                form>
                <div class="row" >
                    <div class="col-sm-6" v-for="(blog,index) in blogList" style="margin-top: 20px;">
                        <div class="card">
                            <div class="card-img-top">
                                <img :src="'img/'+(index+1)+'.jpg'" style="height: auto;width: 100%"/>
                            div>
                            <div class="card-body">
                                <h5 class="card-title">{{blog.title}}h5>
                                <p>{{blog.author}} 发布于 {{blog.createTime}}p>
                                <a :href="'blog.html?id='+blog.id" style="font-weight: bold">...morea>
                            div>
                        div>
                    div>
                div>
            div>
            <div class="col-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">Springboota>
                    li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">ESa>
                    li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">杂谈a>
                    li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">笔记a>
                    li>
                ul>
            div>
        div>
    div>
    
    <script src="./js/vue.js">script>
    <script src="./js/axios.min.js">script>
    <script>
    
        var app ;
        app = new Vue({
            el:'#app',
            data:{
                blogList:[],
                keyword:'',
                duration:''
            },
            methods:{
                getBlogs:function () {
                    console.log("getBlogs");
                    var that = this;
                    axios.get("http://localhost:8080/blogs",{}).then(function (response) {
                        that.blogList = response.data;
                    })
                },
                searchWithMysql:function () {
                    console.log("searchWithMysql");
                    var that = this;
                    var param = {"type":"mysql","keyword":that.keyword};
                    axios.post("http://localhost:8080/search",param).then(function (response) {
                        that.blogList = response.data.list;
                        that.duration = response.data.duration;
                    })
                },
                searchWithEs:function () {
                    console.log("searchWithEs");
                    var that = this;
                    var param = {"type":"es","keyword":that.keyword};
                    axios.post("http://localhost:8080/search",param).then(function (response) {
                        that.blogList = response.data.list;
                        that.duration = response.data.duration;
                    })
                }
            },
            created:function () {
                this.getBlogs();
            }
        })
    
    
    script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113

    然后在同级目录创建详细页面blog.html

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-grid.min.css">
        <link rel="stylesheet" href="css/bootstrap-reboot.min.css">
        <style>
            img {
                height: auto;
                width: 100%;
            }
        style>
    head>
    <body>
    <div class="container">
        <div class="row" style="margin-top: 20px;">
            <div class="col-12">
                <h2>
                    Springboot + es 构建博客检索系统
                h2>
            div>
        div>
    
        <div class="row" style="margin-top: 20px;" id="app">
            <div class="col-9">
    
                <h4 id="title">{{title}}h4>
                <span>作者:{{author}} | 发布时间:{{createTime}}span>
    
                <div v-html="content" style="width: 100%;height: auto;">
    
                div>
            div>
            <div class="col-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">Springboota>
                    li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">ESa>
                    li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">杂谈a>
                    li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">笔记a>
                    li>
                ul>
            div>
        div>
    div>
    <script src="./js/vue.js">script>
    <script src="./js/axios.min.js">script>
    <script src="./js/marked.js">script>
    <script>
    
        function getQueryVariable(variable)
        {
            var query = window.location.search.substring(1);
            var vars = query.split("&");
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
            }
            return(false);
        }
    
        var app = new Vue({
            el: '#app',
            data: {
                title: '',
                author: '',
                createTime: '',
                content: ''
            },
            methods: {
                blog: function () {
                    console.log("blog");
                    var that = this;
                    var id = getQueryVariable("id");
                    axios.get('http://localhost:8080/blog/'+id, {}).then(function (response) {
                        that.title = response.data.title;
                        that.author = response.data.author;
                        that.createTime = response.data.createTime;
                        that.content = marked(response.data.content);
                    })
                }
            },
            created: function () {
                this.blog();
            }
        })
    script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99

    启动项目在浏览器中访问http://localhost:8080/并做相应测试。
    在这里插入图片描述

  • 相关阅读:
    力扣刷题-数组-螺旋矩阵
    一文读懂Kotlin的数据流
    比特币白皮书中文翻译:【比特币:一种点对点的电子现金系统】
    go实现grpc-快速开始
    从底层看 Redis 的五种数据类型
    2022年6月电子学会Python等级考试试卷(三级)答案解析
    删除有序数组里的重复项 -力扣(Java)
    数学建模学习(81):群粒子算法求解最值(模板)
    动态负荷对电力系统摆幅曲线的影响研究(Matlab代码实现)
    gitlab,从A仓库迁移某个工程到B仓库,保留提交记录
  • 原文地址:https://blog.csdn.net/qq_32091929/article/details/127155358