【SpringBoot】SpringBoot集成ElasticSearch

这篇具有很好参考价值的文章主要介绍了【SpringBoot】SpringBoot集成ElasticSearch。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

第一步,导入jar包,注意这里的jar包版本可能和你导入的不一致,所以需要修改

<properties>
<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
<!-- elasticsearch -->
<!--es客户端-->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.6.2</version>
</dependency>

<!--springboot的elasticsearch服务-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

第二步,编写配置类

这段代码是一个基本的 Elasticsearch Java 客户端的配置类,用于创建一个 RestHighLevelClient 实例。

其中 RestHighLevelClient 是 Elasticsearch Java 客户端的高级别别名,是基于 LowLevelClient 之上的封装,提供了一些更加方便的方法和功能。

在这段代码中,使用了 @Value 注解来注入三个配置项,包括 hostname,port 和 scheme。这三个配置项分别表示 Elasticsearch 服务器的主机名或 IP 地址,端口号和通信协议。然后使用RestClient.builder() 方法来创建一个 RestClient 实例,传入 Elasticsearch 服务器的地址和端口号,最后将 RestClient 实例传入 RestHighLevelClient 的构造函数中,即可创建一个 RestHighLevelClient 实例。

需要注意的是,这段代码中的 RestHighLevelClient 实例是一个单例对象,只需要在应用程序启动时创建一次即可,因此这个类应该被配置为一个 Spring Bean,以便在需要时注入到其他类中使用。

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {

    @Value("${elasticSearch.hostname}")
    private String hostname;

    @Value("${elasticSearch.port}")
    private Integer port;

    @Value("${elasticSearch.scheme}")
    private String scheme;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(hostname,port,scheme))
        );
    }
}

第三步,填写yml

elasticSearch:
  hostname: 127.0.0.1
  port: 9200
  scheme: http

第四步,编写util类

这是一个Java类,实现了Elasticsearch API的一些基本功能。它定义了创建、检查是否存在、删除索引、添加、修改和删除文档以及搜索文档的方法。该类使用Elasticsearch API的RESTful客户端来执行这些操作。

以下是每种方法的概述:

  • createIndex(字符串索引):使用给定的名称创建一个索引。
  • existIndex(字符串索引):检查是否存在具有给定名称的索引。
  • deleteIndex(字符串索引):删除具有给定名称的索引。
  • addDocument(动态动态,字符串索引):使用给定的名称将文档添加到索引中。
  • existDocument(字符串索引,字符串文档):检查具有给定ID的文档是否存在于具有给定名称的索引中。
  • getDocument(字符串索引,字符串文档):从具有给定名称的索引中检索具有给定ID的文档。
  • updateDocument(动态动态、字符串索引、字符串文档):在具有给定名称的索引中更新具有给定ID的文档。
  • deleteDocument(字符串索引,字符串文档):从具有给定名称的索引中删除具有给定ID的文档。
  • bulkAddDocument(List<Dynamic>dynamics):在一个批次中将多个具有给定名称的文档添加到索引中。
  • searchDocument(字符串索引):根据搜索查询在索引中搜索具有给定名称的文档。
import com.alibaba.fastjson.JSON;
import com.wangfugui.apprentice.dao.domain.Dynamic;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @since JDK 1.8.0
 */
@Component
@Slf4j
public class ElasticSearchUtil {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    //索引的创建
    public CreateIndexResponse createIndex(String index) throws IOException {
        //1.创建索引的请求
        CreateIndexRequest request = new CreateIndexRequest(index);
        //2客户端执行请求,请求后获得响应
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        log.info("索引的创建{}", response);
        return response;
    }

    //索引是否存在
    public Boolean existIndex(String index) throws IOException {
        //1.创建索引的请求
        GetIndexRequest request = new GetIndexRequest(index);
        //2客户端执行请求,请求后获得响应
        boolean exist = client.indices().exists(request, RequestOptions.DEFAULT);
        log.info("索引是否存在-----" + exist);
        return exist;
    }

    //删除索引
    public Boolean deleteIndex(String index) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        log.info("删除索引--------" + delete.isAcknowledged());
        return delete.isAcknowledged();
    }

    //添加文档
    public IndexResponse addDocument(Dynamic dynamic, String index) throws IOException {
        IndexRequest request = new IndexRequest(index);
        //设置超时时间
        request.timeout("1s");
        //将数据放到json字符串
        request.source(JSON.toJSONString(dynamic), XContentType.JSON);
        //发送请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        log.info("添加文档-------" + response.toString());
        log.info("添加文档-------" + response.status());
        return response;
    }

    //文档是否存在
    public Boolean existDocument(String index, String documents) throws IOException {
        //文档的 没有index
        GetRequest request = new GetRequest(index, documents);
        //没有indices()了
        boolean exist = client.exists(request, RequestOptions.DEFAULT);
        log.info("文档是否存在-----" + exist);
        return exist;
    }

    //获取文档
    public GetResponse getDocument(String index, String documents) throws IOException {
        GetRequest request = new GetRequest(index, documents);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        log.info("获取文档-----" + response.getSourceAsString());
        log.info("获取文档-----" + response);
        return response;
    }

    //修改文档
    public UpdateResponse updateDocument(Dynamic dynamic, String index, String documents) throws IOException {

        //修改是id为1的
        UpdateRequest request = new UpdateRequest(index, documents);
        request.timeout("1s");
        request.doc(JSON.toJSONString(dynamic), XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        log.info("修改文档-----" + response);
        log.info("修改文档-----" + response.status());

        return response;
    }


    //删除文档
    public RestStatus deleteDocument(String index, String documents) throws IOException {
        DeleteRequest request = new DeleteRequest(index, documents);
        request.timeout("1s");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        log.info("删除文档------" + response.status());
        return response.status();
    }

    //批量添加文档
    public BulkResponse bulkAddDocument(List<Dynamic> dynamics) throws IOException {

        //批量操作的Request
        BulkRequest request = new BulkRequest();
        request.timeout("1s");

        //批量处理请求
        for (int i = 0; i < dynamics.size(); i++) {
            request.add(
                    new IndexRequest("lisen_index")
                            .id("" + (i + 1))
                            .source(JSON.toJSONString(dynamics.get(i)), XContentType.JSON)
            );
        }
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        //response.hasFailures()是否是失败的
        log.info("批量添加文档-----" + response.hasFailures());

//        结果:false为成功 true为失败
        return response;
    }


    //查询文档
    public SearchResponse searchDocument(String index) throws IOException {
        SearchRequest request = new SearchRequest(index);
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置了高亮
        sourceBuilder.highlighter();
        //term name为cyx1的
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "cyx1");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        log.info("查询文档-----" + JSON.toJSONString(response.getHits()));
        log.info("=====================");
        for (SearchHit documentFields : response.getHits().getHits()) {
            log.info("查询文档--遍历参数--" + documentFields.getSourceAsMap());
        }
        return response;
    }

    public IndexResponse addDocumentId(Dynamic dynamic, String index, String id) throws IOException {
        IndexRequest request = new IndexRequest(index);
        //设置超时时间
        request.id(id);
        //将数据放到json字符串
        request.source(JSON.toJSONString(dynamic), XContentType.JSON);
        //发送请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        log.info("添加文档-------" + response.toString());
        log.info("添加文档-------" + response.status());
        return response;
    }
}

第五步,编写controller类

这是一个Java类,实现了Elasticsearch API的一些基本功能。它定义了用于创建、检查存在性、删除索引、添加、修改和删除文档,以及搜索文档的方法。该类使用Elasticsearch API的RESTful客户端执行这些操作。

以下是每个方法的概述:

  • createIndex(String index) 创建索引的方法。
  • existIndex(String index) 检查给定名称的索引是否存在的方法。
  • deleteIndex(String index) 删除给定名称的索引的方法。
  • addDocument(Dynamic dynamic, String index) 将文档添加到给定名称的索引的方法。
  • existDocument(String index, String documents) 检查给定名称的索引中是否存在具有给定ID的文档的方法。
  • getDocument(String index, String documents) 从给定名称的索引中检索具有给定ID的文档的方法。
  • updateDocument(Dynamic dynamic, String index, String documents) 在给定名称的索引中更新具有给定ID的文档的方法。
  • deleteDocument(String index, String documents) 从给定名称的索引中删除具有给定ID的文档的方法。
  • bulkAddDocument(List dynamics) 在单个批处理中将多个文档添加到给定名称的索引的方法。
  • searchDocument(String index) 基于搜索查询在给定名称的索引中搜索文档的方法。
import com.wangfugui.apprentice.common.util.ElasticSearchUtil;
import com.wangfugui.apprentice.common.util.ResponseUtils;
import com.wangfugui.apprentice.dao.domain.Dynamic;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @since JDK 1.8.0
 */
@RestController
@RequestMapping("/elasticSearch")
@Api(tags = "elasticSearch操作")
public class ElasticSearchController {

    @Autowired
    private ElasticSearchUtil elasticSearchUtil;

    /**索引的创建*/
    @PostMapping("/createIndex")
    @ApiOperation("索引的创建")
    public ResponseUtils createIndex(@RequestParam String index) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.createIndex(index));
    }

    /**索引是否存在*/
    @GetMapping("/existIndex")
    @ApiOperation("索引是否存在")
    public ResponseUtils existIndex(@RequestParam String index) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.existIndex(index));
    }

    /**删除索引*/
    @DeleteMapping("/deleteIndex")
    @ApiOperation("删除索引")
    public ResponseUtils deleteIndex(@RequestParam String index) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.deleteIndex(index));
    }

    /**添加文档*/
    @PostMapping("/addDocument")
    @ApiOperation("添加文档随机id")
    public ResponseUtils addDocument(@RequestBody Dynamic dynamic, @RequestParam String index) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.addDocument(dynamic,index));
    }

    /**添加文档*/
    @PostMapping("/addDocument")
    @ApiOperation("添加文档自定义id")
    public ResponseUtils addDocumentId(@RequestBody Dynamic dynamic, @RequestParam String index,@RequestParam String id) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.addDocumentId(dynamic,index,id));
    }

    /**文档是否存在*/
    @GetMapping("/existDocument")
    @ApiOperation("文档是否存在")
    public ResponseUtils existDocument(@RequestParam String index, @RequestParam String documents) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.existDocument(index,documents));
    }

    /**获取文档*/
    @GetMapping("/getDocument")
    @ApiOperation("获取文档")
    public ResponseUtils getDocument(@RequestParam String index, @RequestParam String documents) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.getDocument(index,documents));
    }

    /**修改文档*/
    @ApiOperation("修改文档")
    @PutMapping("/updateDocument")
    public ResponseUtils updateDocument(@RequestBody Dynamic dynamic, @RequestParam String index, @RequestParam String documents) throws IOException {

        return ResponseUtils.success(elasticSearchUtil.updateDocument(dynamic,index,documents));
    }


    /**删除文档*/
    @ApiOperation("删除文档")
    @DeleteMapping("/deleteDocument")
    public ResponseUtils deleteDocument(@RequestParam String index, @RequestParam String documents) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.deleteDocument(index,documents));
    }

    /**批量添加文档*/
    @ApiOperation("批量添加文档")
    @PostMapping("/bulkAddDocument")
    public ResponseUtils bulkAddDocument(@RequestBody List<Dynamic> dynamics) throws IOException {

        return ResponseUtils.success(elasticSearchUtil.bulkAddDocument(dynamics));
    }


    /**查询文档*/
    @ApiOperation("查询文档")
    @GetMapping("/searchDocument")
    public ResponseUtils searchDocument(@RequestParam String index) throws IOException {
        return ResponseUtils.success(elasticSearchUtil.searchDocument(index));
    }


}

第六步,测试即可

【SpringBoot】SpringBoot集成ElasticSearch

成功!!文章来源地址https://www.toymoban.com/news/detail-443304.html

到了这里,关于【SpringBoot】SpringBoot集成ElasticSearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot 集成 Elasticsearch

    版本说明详见 Elasticsearch 下载 kibana下载 ik分词器下载 2.1 解压,在elasticsearch-7.8.0plugins 路径下新建ik目录 2.2 将ik分词器解压放入ik目录 2.3 扩展词汇测试示例 2.3.1 ik/config 目录下新建custom.dic文件 2.3.2 编辑custom.dic文件,加入新词汇 注意:custom.dic文件内容的格式的编码为UTF-8格

    2024年02月14日
    浏览(28)
  • SpringBoot3集成ElasticSearch

    目录 一、简介 二、环境搭建 1、下载安装包 2、服务启动 三、工程搭建 1、工程结构 2、依赖管理 3、配置文件 四、基础用法 1、实体类 2、初始化索引 3、仓储接口 4、查询语法 五、参考源码 标签:ElasticSearch8.Kibana8; Elasticsearch是一个分布式、RESTful风格的搜索和数据分析引擎

    2024年02月12日
    浏览(28)
  • 1.springboot 集成elasticsearch组件

    1.前置条件已经安装和搭建好了elasticsearch中间件 一:项目中引入elasticsearch相关依赖 我安装的elasticsearch版本是7.10.2 对应依赖的版本保持一致 此处省略springboot 搭建及必要的依赖项 二:项目配置文件里配置上elasticsearch相关的信息 application.yml 三:工程里编写elasticsearch相关的配

    2024年02月09日
    浏览(23)
  • springBoot 集成阿里云Elasticsearch

        原系统使用tcp方式接入ES,使用 ElasticsearchTemplate API方式交互ES。原springes的yml配置如下:         由于接入阿里云的ES,且加上了X-PACK验证模式,必须有用户名和密码。故拉取新的分支支持阿里云ES的配置。         由于A项目是SpringMvc方式的配置,下面讲一下遇到的问题

    2024年02月16日
    浏览(27)
  • SpringBoot项目集成ElasticSearch服务

    本文已收录于专栏 《中间件合集》   Spring boot的版本是: 2.3.12   ElasticSearch的版本是:7.6.2   在我们的项目中经常会遇到对于字符串的一些操作,例如对于字符串的分词,通过一个词去查找对应的原文(全文搜索)。那可能有人就会问了,使用mysql的模糊查询也可以根据

    2024年02月12日
    浏览(34)
  • 【极光系列】springBoot集成elasticsearch

    直接下载解压可用 https://gitee.com/shawsongyue/aurora.git 模块:aurora_elasticsearch tips:注意es客户端版本要与java依赖版本一致,目前使用7.6.2版本 elasticsearch 7.6.2版本客户端下载: https://www.elastic.co/cn/downloads/elasticsearch 1.下载对应版本资源包 登录页面–》View path releases–》选择7.6.2版本

    2024年01月25日
    浏览(30)
  • springboot集成ElasticSearch版本号问题

    1.本地安装es版本 2.spring-boot-starter-parent 版本2.2.13对应自动集成的elasticsearch包版本是6.8.15 springboot和es版本对应关系查询地址  https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#repositories故springboot junit测试时查询报错    解决方案 1.将springboot包版本下降到2.1.3RELEASE就

    2024年02月11日
    浏览(30)
  • SpringBoot集成Elasticsearch搜索引擎

    Elasticsearch是一个基于Lucene的搜索引擎,它提供了实时、可扩展和可伸缩的搜索功能。Spring Boot是一个用于构建新Spring应用的起点,它旨在简化开发人员的工作,使其能够快速地构建可扩展的、可维护的应用程序。 在现代应用程序中,搜索功能是非常重要的。它可以帮助用户快

    2024年02月19日
    浏览(38)
  • SpringBoot 集成Elasticsearch简单八步

         Elasticsearch是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别的数据。  Elasticsearch也使用Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是通过简单的RE

    2024年02月17日
    浏览(33)
  • ElasticSearch完整入门及springboot集成

    Elaticsearch,简称为es,es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是 通过

    2024年02月09日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包