千家信息网

Spring Boot怎样进行整合elasticsearch

发表于:2026-11-02 作者:千家信息网编辑
千家信息网最后更新 2026年11月02日,这篇文章给大家介绍Spring Boot怎样进行整合elasticsearch,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。一、简介我们的应用经常需要添加检索功能,开源的 Ela
千家信息网最后更新 2026年11月02日Spring Boot怎样进行整合elasticsearch

这篇文章给大家介绍Spring Boot怎样进行整合elasticsearch,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

一、简介

我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选。他可以快速的存储、搜索和分析海量数据。Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持;
Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用 多shard(分片)的方式保证数据安全,并且提供自动resharding的功能,github 等大型的站点也是采用了ElasticSearch作为其搜索服务,

二、安装elasticsearch

我们采用 docker镜像安装的方式。

#下载镜像docker pull elasticsearch#启动镜像,elasticsearch 启动是会默认分配2G的内存 ,我们启动是设置小一点,防止我们内存不够启动失败#9200是elasticsearch 默认的web通信接口,9300是分布式情况下,elasticsearch个节点通信的端口docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es01 5c1e1ecfe33a

访问 127.0.0.1:9200 如下图,说明安装成功

三、elasticsearch的一些概念

  • 以 员工文档 的形式存储为例:一个文档代表一个员工数据。存储数据到 ElasticSearch 的行为叫做索引 ,但在索引一个文档之前,需要确定将文档存 储在哪里。

  • 一个 ElasticSearch 集群可以 包含多个索引 ,相应的每个索引可以包含多个类型。这些不同的类型存储着多个文档 ,每个文档又有 多个 属性 。

  • 类似关系:

    • 索引-数据库

    • 类型-表

    • 文档-表中的记录 - 属性-列

elasticsearch使用可以参早官方文档,在这里不在讲解。

四、整合 elasticsearch

创建项目 springboot-elasticsearch,引入web支持
SpringBoot 提供了两种方式操作elasticsearch,Jest 和 SpringData。

Jest 操作 elasticsearch

Jest是ElasticSearch的Java HTTP Rest客户端。

ElasticSearch已经有一个Java API,ElasticSearch也在内部使用它,但是Jest填补了空白,它是ElasticSearch Http Rest接口缺少的客户端。

1. pom.xml
    4.0.0    com.gf    springboot-elasticsearch    0.0.1-SNAPSHOT    jar    springboot-elasticsearch    Demo project for Spring Boot            org.springframework.boot        spring-boot-starter-parent        2.1.1.RELEASE                         UTF-8        UTF-8        1.8                        org.springframework.boot        spring-boot-starter-data-elasticsearch                        io.searchbox            jest            5.3.3                            org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-starter-test            test                                                    org.springframework.boot                spring-boot-maven-plugin                        

####2. application.properties

spring.elasticsearch.jest.uris=http://127.0.0.1:9200
3. Article
package com.gf.entity;import io.searchbox.annotations.JestId;public class Article {    @JestId    private Integer id;    private String author;    private String title;    private String content;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getAuthor() {        return author;    }    public void setAuthor(String author) {        this.author = author;    }    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;    }    @Override    public String toString() {        final StringBuilder sb = new StringBuilder( "{\"Article\":{" );        sb.append( "\"id\":" )                .append( id );        sb.append( ",\"author\":\"" )                .append( author ).append( '\"' );        sb.append( ",\"title\":\"" )                .append( title ).append( '\"' );        sb.append( ",\"content\":\"" )                .append( content ).append( '\"' );        sb.append( "}}" );        return sb.toString();    }}
4. springboot测试类
package com.gf;import com.gf.entity.Article;import io.searchbox.client.JestClient;import io.searchbox.core.Index;import io.searchbox.core.Search;import io.searchbox.core.SearchResult;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.test.context.junit4.SpringRunner;import java.io.IOException;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringbootElasticsearchApplicationTests {    @Autowired    JestClient jestClient;    @Test    public void createIndex() {        //1. 给ES中索引(保存)一个文档        Article article = new Article();        article.setId( 1 );        article.setTitle( "好消息" );        article.setAuthor( "张三" );        article.setContent( "Hello World" );        //2. 构建一个索引        Index index = new Index.Builder( article ).index( "gf" ).type( "news" ).build();        try {            //3. 执行            jestClient.execute( index );        } catch (IOException e) {            e.printStackTrace();        }    }    @Test    public void search() {        //查询表达式        String query = "{\n" +                "    \"query\" : {\n" +                "        \"match\" : {\n" +                "            \"content\" : \"hello\"\n" +                "        }\n" +                "    }\n" +                "}";        //构建搜索功能        Search search = new Search.Builder( query ).addIndex( "gf" ).addType( "news" ).build();        try {            //执行            SearchResult result = jestClient.execute( search );            System.out.println(result.getJsonString());        } catch (IOException e) {            e.printStackTrace();        }    }}

Jest的更多api ,可以参照github的文档:https://github.com/searchbox-io/Jest

SpringData 操作 elasticsearch

1. application.properties
spring.data.elasticsearch.cluster-name=elasticsearchspring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
2. Book
package com.gf.entity;@Document( indexName = "gf" , type = "book")public class Book {    private Integer id;    private String bookName;    private String author;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getBookName() {        return bookName;    }    public void setBookName(String bookName) {        this.bookName = bookName;    }    public String getAuthor() {        return author;    }    public void setAuthor(String author) {        this.author = author;    }    @Override    public String toString() {        final StringBuilder sb = new StringBuilder( "{\"Book\":{" );        sb.append( "\"id\":" )                .append( id );        sb.append( ",\"bookName\":\"" )                .append( bookName ).append( '\"' );        sb.append( ",\"author\":\"" )                .append( author ).append( '\"' );        sb.append( "}}" );        return sb.toString();    }}
3. BookRepository
package com.gf.repository;import com.gf.entity.Book;import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;import java.util.List;public interface BookRepository extends ElasticsearchRepository{    List findByBookNameLike(String bookName);}
4. springboot 测试类
package com.gf;import com.gf.entity.Article;import com.gf.entity.Book;import com.gf.repository.BookRepository;import io.searchbox.client.JestClient;import io.searchbox.core.Index;import io.searchbox.core.Search;import io.searchbox.core.SearchResult;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.test.context.junit4.SpringRunner;import java.io.IOException;import java.util.List;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringbootElasticsearchApplicationTests {    @Autowired    BookRepository bookRepository;    @Test    public void createIndex2(){        Book book = new Book();        book.setId(1);        book.setBookName("西游记");        book.setAuthor( "吴承恩" );        bookRepository.index( book );    }    @Test    public void useFind() {        List list = bookRepository.findByBookNameLike( "游" );        for (Book book : list) {            System.out.println(book);        }    }}

我们启动测试 ,发现报错 。

这个报错的原因是springData的版本与我elasticsearch的版本有冲突,下午是springData官方文档给出的适配表。

我们使用的springdata elasticsearch的 版本是3.1.3 ,对应的版本应该是6.2.2版本,而我们是的 elasticsearch 是 5.6.9,所以目前我们需要更换elasticsearch的版本为6.X

docker pull elasticsearch:6.5.1docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es02 镜像ID

访问127.0.0.1:9200

集群名为docker-cluster,所以我们要修改application.properties的配置了

spring.data.elasticsearch.cluster-name=docker-clusterspring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

关于Spring Boot怎样进行整合elasticsearch就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

文档 索引 版本 数据 搜索 整合 功能 多个 镜像 存储 方式 更多 类型 测试 内存 内容 分布式 员工 官方 客户 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 深圳恒合互联网络科技有限公司 美国互联网保险保险科技 科技信息互联网 互联网金融 金融科技 中国 科技 互联网 杭州互联网科技公司 亿人帮互联网科技 宁夏众和广鑫互联网科技有限公司 全球顶尖互联网科技公司 语蝶互联网科技有限公司 宜昌元轩互联网科技有限公司 玉溪新华互联网科技好不好 科技互联网海报 国大互联网教育科技有限公司薪资 高科技互联网套路 中天科技中国工业互联网 九思连强互联网电子科技有限公司 福仕德教育科技互联网 互联网领先科技成果宣传视频 互联网高科技绘画 南京欣网互联网络科技有限公司 腾讯科技 互联网女皇 美国互联网黑科技 互联网巨头投资的硬核科技 厦门千工互联网科技有限公司 移动互联网年度科技创新 深圳无忧互联网科技 广州百诚互联网科技有限公司官网 上海乐五互联网科技有限公司 互联网科技职业技能培训学校
0