打开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
首先在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;
}
然后在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> {
}
然后在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";
}
}
在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>
启动项目在浏览器里访问http://localhost:8080/,控制台也打出了查出的数据行数。
首先在pom.xml中添加ES依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
然后在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;
}
当我们的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> {
}
编写测试用例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());
}
}
打开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);
}
然后在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;
}
}
在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>
然后在同级目录创建详细页面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>