SpringBoot 整合 elasticsearch 实例

时间:2022-06-22
本文章向大家介绍SpringBoot 整合 elasticsearch 实例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、下载 并启动 elasticsearch

下载地址:https://www.elastic.co/downloads/past-releases

选择一个版本,下载

博主这里测试使用的是 2.4.4

下载方式可以选择 ZIP 包

启动的话,windows 和 mac 有些细微区别

windows :进入文件目录下的 bin,然后点击 elasticsearch.bat 即可

mac:在终端执行命令 bin/elasticsearch

二、配置 Maven

<!-- Spring Boot Elasticsearch 依赖 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>


<properties>
   <elasticsearch.version>2.4.4</elasticsearch.version>
</properties>

添加 spring-boot-starter-data-elasticsearch 依赖,并设置 elasticsearch 版本为 2.4.4

ES 和 SpirngBoot 版本参考:

https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix

三、修改 application.properties

#Project
server.port=8080
debug=true
server.context-path=/chuyun
# DataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/chuyun?characterEncodeing=utf-8&useSSL=false
# JPA
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#Thymeleaf
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.cache-period=0
spring.template.cache=false
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:templates/
spring.thymeleaf.suffix=.html
#Elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s

主要是添加最后面两条

四、创建 ES Bean 和 Repository

Article.java

package com.liuyanzhao.chuyun.domain.es;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.Id;
import java.util.Date;
/**
 * @author 言曌
 * @date 2018/1/22 下午4:45
 */
@Document(indexName="chuyun",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
public class Article {
    //文章ID,这里必须为 id
    @Id
    private Long id;
    //标题
    private String title;
    //内容
    private String content;
    //浏览量
    private Integer viewCount;
    //发布时间
    private Date createTime;
    //更新时间
    private Date updateTime;
    public Article() {
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getViewCount() {
        return viewCount;
    }
    public void setViewCount(Integer viewCount) {
        this.viewCount = viewCount;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + ''' +
                ", content='" + content + ''' +
                ", viewCount=" + viewCount +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}

ArticleRepository.java

package com.liuyanzhao.chuyun.repository.es;
import com.liuyanzhao.chuyun.domain.es.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
 * @author 言曌
 * @date 2018/1/22 下午5:05
 */
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
    Page<Article> findDistinctByTitleContainingOrContentContaining(String title, String content, Pageable pageable);
}

五、创建测试类

ArticleRepositoryTest.java

package com.liuyanzhao.chuyun.repository.es;
import com.liuyanzhao.chuyun.domain.es.Article;
import com.liuyanzhao.chuyun.entity.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
/**
 * @author 言曌
 * @date 2018/1/21 下午5:03
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ArticleRepositoryTest {
    @Autowired
    private ArticleRepository articleRepository;
    @Before
    public void initRepositoryData() {
        //清除所有数据
        articleRepository.deleteAll();
        Article article = new Article();
        article.setId((long) 1);
        article.setTitle("《蝶恋花》");
        article.setContent("槛菊愁烟兰泣露,罗幕轻寒,燕子双飞去。明月不谙离恨苦,斜光到晓穿朱户。昨夜西风凋碧树,独上高楼,望尽天涯路。欲寄彩笺兼尺素,山长水阔知何处?");
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setViewCount(678);
        articleRepository.save(article);
        Article article2 = new Article();
        article2.setId((long) 2);
        article2.setTitle("《蝶恋花》");
        article2.setContent("伫倚危楼风细细,望极春愁,黯黯生天际。草色烟光残照里,无言谁会凭阑意。拟把疏狂图一醉,对酒当歌,强乐还无味。衣带渐宽终不悔,为伊消得人憔悴。");
        article2.setCreateTime(new Date());
        article2.setUpdateTime(new Date());
        article.setViewCount(367);
        articleRepository.save(article2);
        Article article3 = new Article();
        article3.setId((long) 3);
        article3.setTitle("《青玉案·元夕》");
        article3.setContent("东风夜放花千树,更吹落,星如雨。宝马雕车香满路。凤箫声动,玉壶光转,一夜鱼龙舞。蛾儿雪柳黄金缕,笑语盈盈暗香去。众里寻他千百度,蓦然回首,那人却在,灯火阑珊处。");
        article3.setCreateTime(new Date());
        article3.setUpdateTime(new Date());
        article3.setViewCount(786);
        articleRepository.save(article3);
    }
    @Test
    public void findDistinctByTitleContainingOrContentContainingTest() throws Exception {
        Pageable pageable = new PageRequest(0,20);
        String title = "我爱罗琪";
        String content = "花千树";
        Page<Article> page = articleRepository.findDistinctByTitleContainingOrContentContaining(title, content, pageable);
        System.out.println(page);
        System.out.println("---start---");
        for(Article article : page.getContent()) {
            System.out.println(article.toString());
        }
        System.out.println("---end---");
    }
}

运行 @Test 注解的方法

根据 title 和 content 内容查到一条数据

修改 title 和 content

String title = "蝶恋";
String content = "东风";

查到三条数据

六、访问 http://localhost:9200/_plugin/head/

因为上一篇文章中,我们讲了装一个 head 插件,现在我们就能看到里面的数据了(多余的数据是之前测试的)

七、新建 Controller 类

ArticleController.java

package com.liuyanzhao.chuyun.controller;
import com.liuyanzhao.chuyun.domain.es.Article;
import com.liuyanzhao.chuyun.repository.es.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * @author 言曌
 * @date 2018/1/22 下午9:07
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleRepository ArticleRepository;
    @RequestMapping("")
    public List<Article> list(@RequestParam(value = "title", required = false) String title,
                                @RequestParam(value = "content", required = false) String content,
                                @RequestParam(value = "pageIndex", defaultValue = "0") int pageIndex,
                                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        Pageable pageable = new PageRequest(pageIndex, pageSize);
        Page<Article> page = ArticleRepository.findDistinctByTitleContainingOrContentContaining(title, content, pageable);
        return page.getContent();
    }
}

因为之前在 测试类 里已经给 elasticsearch 添加了数据

所有现在可以在浏览器上访问:

http://localhost:8080/chuyun/article?title=浪淘沙&content=伊人