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;
目录
相关文章
|
12月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。
|
人工智能 数据可视化 测试技术
Postman 性能测试教程:快速上手 API 压测
本文介绍API上线后因高频调用导致服务器告警,通过Postman与Apifox进行压力测试排查性能瓶颈。对比两款工具在批量请求、断言验证、可视化报告等方面的优劣,探讨API性能优化策略及行业未来发展方向。
Postman 性能测试教程:快速上手 API 压测
存储 JSON Java
1096 0
|
人工智能 数据可视化 测试技术
AI 时代 API 自动化测试实战:Postman 断言的核心技巧与实战应用
AI 时代 API 自动化测试实战:Postman 断言的核心技巧与实战应用
1442 11
|
XML 安全 测试技术
【干货满满】分享什么是API接口测试
API接口测试是验证应用程序编程接口功能、性能、安全性及兼容性的关键环节,通过模拟请求并验证响应结果,确保接口能正确处理各种输入和场景。测试内容涵盖功能验证、性能评估、安全防护、兼容性验证及系统可靠性。相比UI测试,API测试无需界面依赖,支持数据驱动与自动化,适用于持续集成流程。常见接口类型包括RESTful、SOAP和GraphQL API,广泛应用于电商、金融及社交平台,保障系统间数据交互的安全与高效。
|
监控 安全 测试技术
API测试工具评测:Apipost与Apifox的优劣深度解读
本文对比了Apipost与Apifox在API设计、数据建模、代码生成、测试能力、协作权限、性能监控、插件生态、文档管理及安全合规等方面的差异。Apifox在专业性、自动化、扩展性及团队协作上表现更优,尤其适合中大型项目与复杂管理需求,而Apipost功能较基础,适用于轻量级使用场景。
|
JSON 安全 测试技术
什么是API接口测试?这可能是全网最全的教程了!
API 是应用程序间的“中间人”,用于实现通信和数据交换。随着微服务架构的普及,API 数量激增,其质量对系统稳定性至关重要。API 测试可验证功能、性能与安全性,帮助开发者在部署前发现并修复问题,提升系统可靠性。测试内容包括请求方法、URL、请求头、请求体、响应状态码与响应数据等。常用工具如 Postman、AREX 可辅助测试,确保 API 在不同场景下的正确性与稳定性。
|
JSON JavaScript 测试技术
用Postman玩转电商API:一键测试+自动化请求教程
Postman 是电商 API 测试的高效工具,涵盖基础配置、自动化测试、环境管理与请求自动化,助你快速提升开发效率。
|
人工智能 监控 安全
API安全测试工具:数字经济的免疫防线
API安全面临漏洞盲区、配置错误与合规碎片三大挑战,传统手段难抵新型风险。破局需构建智能漏洞探针、配置审计中枢与合规映射引擎三位一体防御矩阵。Burp Suite、Noname Security、Traceable AI与板栗看板等工具助力企业实现自动化检测、精准响应与高效合规,打造API安全免疫体系。
|
人工智能 自然语言处理 测试技术
AI时代,Apipost和Apifox如何利用AI技术赋能API研发测试管理所需?
在数字化转型加速背景下,API成为企业互联互通的关键。Apipost与Apifox作为主流工具,在AI赋能方面差异显著。Apipost通过智能参数命名、接口设计自动化、测试用例生成、断言自动化等功能大幅提升研发效率和质量,尤其适合中大型企业及复杂业务场景。相比之下,Apifox功能依赖手动操作较多,适用性更偏向初创或小型项目。随着AI技术发展,Apipost展现出更强的智能化与前瞻性优势,为企业提供高效、稳定的API管理解决方案,助力其在竞争激烈的市场中实现创新突破。
420 0