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

简介: 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;
目录
相关文章
|
4月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。
|
9月前
|
网络协议 Java
SpringBoot快速搭建TCP服务端和客户端
由于工作需要,研究了SpringBoot搭建TCP通信的过程,对于工程需要的小伙伴,只是想快速搭建一个可用的服务.其他的教程看了许多,感觉讲得太复杂,很容易弄乱,这里我只讲效率,展示快速搭建过程。
912 58
|
8月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
937 0
|
5月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
4416 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
|
4月前
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
982 2
|
8月前
|
人工智能 Java 测试技术
SpringBoot 测试实践:单元测试与集成测试
在 Spring Boot 测试中,@MockBean 用于创建完全模拟的 Bean,替代真实对象行为;而 @SpyBean 则用于部分模拟,保留未指定方法的真实实现。两者结合 Mockito 可灵活控制依赖行为,提升测试覆盖率。合理使用 @ContextConfiguration 和避免滥用 @SpringBootTest 可优化测试上下文加载速度,提高测试效率。
430 5
|
7月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
311 0
|
8月前
|
Java API 网络架构
基于 Spring Boot 框架开发 REST API 接口实践指南
本文详解基于Spring Boot 3.x构建REST API的完整开发流程,涵盖环境搭建、领域建模、响应式编程、安全控制、容器化部署及性能优化等关键环节,助力开发者打造高效稳定的后端服务。
1144 1
|
9月前
|
Java
SpringBoot快速搭建WebSocket服务端和客户端
由于工作需要,研究了SpringBoot搭建WebSocket双向通信的过程,其他的教程看了许多,感觉讲得太复杂,很容易弄乱,这里我只展示快速搭建过程。
2579 1
|
11月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现