SpringBoot【集成ElasticSearch 01】2种方式的高级客户端 RestHighLevelClient 使用(依赖+配置+客户端API测试源码)

本文涉及的产品
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: SpringBoot【集成ElasticSearch 01】2种方式的高级客户端 RestHighLevelClient 使用(依赖+配置+客户端API测试源码)

1.方式一

1.1 依赖

【不使用 spring-boot-starter-data-elasticsearch 就可以脱离 springboot 版本的限制,可以自行选择ES的版本】我用的是 springboot 2.2.5.RELEASE 版本,ES部署文件为 elasticsearch-6.4.3.tar.gz,这里只贴出主要依赖:

<!-- ElasticSearch Server -->
<dependency>
  <groupId>org.elasticsearch</groupId>
  <artifactId>elasticsearch</artifactId>
  <version>6.4.3</version>
</dependency>
<!-- Java High Level REST Client -->
<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>elasticsearch-rest-high-level-client</artifactId>
  <version>6.4.3</version>
</dependency>

1.2 配置信息

这里根据elasticsearch服务端的地址进行配置:

@Configuration
public class ElasticSearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")
                ));
        return client;
    }
}

1.3 客户端使用

@SpringBootTest
class EsApiApplicationTests {
  @Autowired
  @Qualifier(value = "restHighLevelClient")
  private RestHighLevelClient client;
  /*1.创建索引*/
  @Test
  void createIndex() throws IOException {
    // 创建请求
    CreateIndexRequest request = new CreateIndexRequest("yz_index");
    // 执行请求,获取响应
    CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
    System.out.println("creatIndex--" + response);
  }
  /*2.获取索引,判断是否存在*/
  @Test
  void getIndex() throws IOException {
    // 创建请求
    GetIndexRequest request = new GetIndexRequest("yz_index");
    // 执行请求,获取响应
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println("getIndex--exists--" + exists);
  }
  /*3.删除索引*/
  @Test
  void deleteIndex() throws IOException {
    // 创建请求
    DeleteIndexRequest request = new DeleteIndexRequest("yz_index");
    // 执行请求
    AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println("deleteIndex--" + response);
  }
  /*4.添加文档*/
  @Test
  void addDocument() throws IOException {
    // 创建对象
    User user = new User("Java虚拟机", 30);
    // 创建索引,即获取索引
    IndexRequest indexRequest = new IndexRequest("yz_index");
    // 添加规则 /index/_doc/id
    indexRequest.id("1");
    indexRequest.timeout(TimeValue.timeValueSeconds(1));
    // 存入对象
    indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
    // 发送请求
    IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
    System.out.println("addDocument--" + response);
  }
  /*5.获取文档是否存在*/
  @Test
  void getDocument() throws IOException {
    // 创建get请求
    GetRequest getRequest = new GetRequest("yz_index", "1");
    // 不获取返回的_source的上下文
    getRequest.fetchSourceContext(new FetchSourceContext(false));
    getRequest.storedFields("_none_");
    // 发送请求
    boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
    System.out.println("addDocument--" + exists);
    /*6.获取文档信息*/
    if (exists) {
      // 创建请求
      GetRequest getRequest1 = new GetRequest("yz_index", "1");
      // 发送请求
      GetResponse response = client.get(getRequest1, RequestOptions.DEFAULT);
      System.out.println("source--" + response.getSource());
      System.out.println("getDocument--" + response.getSourceAsString());
    }
    /*7.更新文档信息*/
    if (exists) {
      // 创建请求
      UpdateRequest updateRequest = new UpdateRequest("yz_index", "1");
      updateRequest.timeout("1s");
      // 修改内容
      User user = new User("小米", 10);
      updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
      UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
      System.out.println("updateDocument--" + response.status());
    }
    /*8.删除文档信息*/
    if (exists) {
      // 创建请求
      DeleteRequest deleteRequest = new DeleteRequest("yz_index", "1");
      deleteRequest.timeout("1s");
      // 修改内容
      DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
      System.out.println("deleteDocument--" + response.status());
    }
  }
  /*9.批量添加文档*/
  @Test
  void batchAddDocument() throws IOException {
    // 批量请求
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("10s");
    // 创建对象
    ArrayList<User> userArrayList = new ArrayList<>();
    userArrayList.add(new User("小米1", 1));
    userArrayList.add(new User("小米2", 2));
    userArrayList.add(new User("小米3", 3));
    userArrayList.add(new User("小米4", 4));
    userArrayList.add(new User("小米5", 5));
    // 添加请求
    for (int i = 0; i < userArrayList.size(); i++) {
      bulkRequest.add(new IndexRequest("yz_index")
          .id("" + (i + 2))
          .source(JSON.toJSONString(userArrayList.get(i)), XContentType.JSON));
    }
    // 执行请求
    BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    System.out.println("batchAddDocument--" + response.status());
  }
  /*10.查询*/
  @Test
  void search() throws IOException {
    // 创建请求
    SearchRequest searchRequest = new SearchRequest("jd_index");
    // 构建搜索条件
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "杜伽");// 精确查询
    searchSourceBuilder.query(termQueryBuilder);
    searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
    searchRequest.source(searchSourceBuilder);
    // 执行请求
    SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
    // 解析查询结果
    System.out.println("search--getHists--" + JSON.toJSONString(response.getHits()));
    for (SearchHit documentFields : response.getHits()) {
      System.out.println("search--getHist--" + documentFields.getSourceAsMap());
    }
  }
}

2.方式二

2.1 依赖

我用的是 springboot 2.5.4【所以spring-boot-starter-data-elasticsearch 的版本也是 2.5.4】此时对应的 elasticsearch 服务端和客户端的版本是 7.12.1 那要部署的ES版本也要是 7.12.1:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2.2 配置信息

spring:
  elasticsearch:
    rest:
      uris: localhost:9200

2.3 客户端使用

@SpringBootTest
class EsStarterApplicationTests {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Test
    void contextLoads() {
    // 由于不同版本的API不同【没有参考价值】,这里不再贴出测试代码。
    }
}

3.注意事项

不同的 elasticsearch 版本有不同的 API 这就给升级造成了阻碍,为了避免这种情况,我们可以使用elasticsearch的 HTTP 客户端 Jest,下篇文章会详细说明。

相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
目录
相关文章
|
3月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
426 0
|
4月前
|
SQL Java 关系型数据库
Dataphin功能Tips系列(53)-离线集成任务如何合理配置JVM资源
本文探讨了将MySQL数据同步至Hive时出现OOM问题的解决方案。
112 5
|
6月前
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
692 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
2月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
140 0
|
3月前
|
人工智能 Java 测试技术
SpringBoot 测试实践:单元测试与集成测试
在 Spring Boot 测试中,@MockBean 用于创建完全模拟的 Bean,替代真实对象行为;而 @SpyBean 则用于部分模拟,保留未指定方法的真实实现。两者结合 Mockito 可灵活控制依赖行为,提升测试覆盖率。合理使用 @ContextConfiguration 和避免滥用 @SpringBootTest 可优化测试上下文加载速度,提高测试效率。
236 6
|
5月前
|
数据可视化 测试技术 API
JMeter、Apipost 与 Postman 的 API 测试对比:为什么 APIPost 是更聪明的选择
API测试如同筹备一场晚宴,选对工具至关重要。JMeter功能强大但上手难,适合专业用户;Postman简单易用,但在复杂场景和团队协作中表现有限;而Apipost则是一款智能高效的“厨房神器”。它性能测试轻松、结果清晰、学习门槛低,并且能一键集成CI/CD流程。对于追求效率与便捷的团队而言,Apipost无疑是更优选择,让API测试如同五星大厨烹饪般丝滑流畅。
|
4月前
|
JSON JavaScript API
MCP 实战:用配置与真实代码玩转 GitHub 集成
MCP 实战:用配置与真实代码玩转 GitHub 集成
1177 4
|
5月前
|
存储 前端开发 数据可视化
Postman vs. Apifox 用于 API 测试全面对比
寻找一款可靠的 API 测试工具?这份对比分析将深入探讨 Postman 和 Apifox 的功能和特性。了解哪款工具最适合您的 API 测试需求。
|
5月前
|
jenkins 测试技术 Shell
利用Apipost轻松实现用户充值系统的API自动化测试
API在现代软件开发中扮演着连接不同系统与模块的关键角色,其测试的重要性日益凸显。传统API测试面临效率低、覆盖率不足及难以融入自动化工作流等问题。Apipost提供了一站式API自动化测试解决方案,支持零代码拖拽编排、全场景覆盖,并可无缝集成CI/CD流程。通过可视化界面,研发与测试人员可基于同一数据源协作,大幅提升效率。同时,Apipost支持动态数据提取、性能压测等功能,满足复杂测试需求。文档还以用户充值系统为例,详细介绍了从创建测试用例到生成报告的全流程,帮助用户快速上手并提升测试质量。
|
5月前
|
监控 安全 测试技术
选择Postman免费版还是付费版,进行 API 测试呢?
深入了解 Postman 免费版和付费版的细节,看看哪一个更适合您的 API 需求。