Elasticsearch8.x版本Java客户端Elasticsearch Java API Client中常用API练习

这篇具有很好参考价值的文章主要介绍了Elasticsearch8.x版本Java客户端Elasticsearch Java API Client中常用API练习。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Es的java API客户端

在Es7.15版本之后,es官方将它的高级客户端RestHighLevelClient标记为弃用状态。同时推出了全新的java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。

Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有Elasticsearch API。且支持所有API数据类型,并且不再有原始JSON Value属性。它是针对Elasticsearch8.0及之后版本的客户端。

maven中引入依赖坐标

  <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>8.12.2</version>
        </dependency>
    <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.12.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
  • 创建连接
@Bean
    public ElasticsearchClient elasticsearchClient(@Value("${elasticsearch.xxxx}") String serverUrl,
                                                   @Value("${elasticsearch.xxxxx}") String apiKey) {

        RestClient restClient = RestClient.builder(
                        HttpHost.create(serverUrl))
                .setDefaultHeaders(new Header[]{new BasicHeader("Authorization", "ApiKey " + apiKey),})
                .build();

        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        return new ElasticsearchClient(transport);

    }
  • 索引index
  @Test
    public void create() throws IOException {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)
        ).build();
        // 使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        // 创建API客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 创建索引
        CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));
        // 响应状态
        Boolean acknowledged = createIndexResponse.acknowledged();
        System.out.println("索引操作 = " + acknowledged);

        // 关闭ES客户端
        transport.close();
        restClient.close();
    }
  • 查询索引
@Test
    public void query() throws IOException {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost",9200)
        ).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 查询索引
        GetIndexResponse getIndexResponse = client.indices().get(e -> e.index("user_test"));
        System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
        System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());

        transport.close();
        restClient.close();
    } 

如果查询的index不存在会在控制台抛出index_not_found_exception

  • 删除索引
 @Test
    public void delete() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 删除索引
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index("user_test"));
        System.out.println("删除操作 = " + deleteIndexResponse.acknowledged());

        transport.close();
        restClient.close();
    }

文档document的操作

  • 添加document
@Test
    public void addDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 向user对象中添加数据
        User user = new User("java客户端", "男", 18);
        // 向索引中添加数据
        CreateResponse createResponse = client.create(e -> e.index("user_test").id("1001").document(user));
        System.out.println("createResponse.result() = " + createResponse.result());

        transport.close();
        restClient.close();
    }

注:index中参数为文档所属的索引名,id中参数为当文档的id,document为文档数据,新版本支持直接传入java对象。

  • 查询document
 @Test
    public void queryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建请求
        GetResponse<User> getResponse = client.get(e -> e.index("user_test").id("1001"), User.class);
        System.out.println("getResponse.source().toString() = " + getResponse.source().toString());

        transport.close();
        restClient.close();
    }

注:如果查不到控制台抛出NullPointerException

  • 修改document
@Test
    public void modifyDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 使用map集合封装需要修改的内容
        Map<String, Object> map = new HashMap<>();
        map.put("name", "java客户端aaa");
        // 构建请求
        UpdateResponse<User> updateResponse = client.update(e -> e.index("user_test").id("1001").doc(map), User.class);
        System.out.println("updateResponse.result() = " + updateResponse.result());

        transport.close();
        restClient.close();
    }
  • 删除document
    @Test
    public void removeDocument() throws  IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建请求
        DeleteResponse deleteResponse = client.delete(e -> e.index("user_test").id("1001"));
        System.out.println("deleteResponse.result() = " + deleteResponse.result());

        transport.close();
        restClient.close();
    }
  • 批量添加document
   @Test
    public void batchAddDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建一个批量数据集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());
        // 调用bulk方法执行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }

批量添加的核心是需要构建一个泛型为BulkOperation的ArrayList集合,实质上是将多个请求包装到一个集合中,进行统一请求,进行构建请求时调用bulk方法,实现批量添加效果。

  • 批量删除
    @Test
    public void batchDeleteDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建一个批量数据集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().delete(
                d -> d.id("1002").index("user_test")).build());
        list.add(new BulkOperation.Builder().delete(
                d -> d.id("1003").index("user_test")).build());
        // 调用bulk方法执行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }
  • 全量查询
    @Test
    public void queryAllDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 全量查询
        SearchResponse<User> searchResponse = client.search(e -> e.index("user_test").query(q -> q.matchAll(m -> m)), User.class);
        HitsMetadata<User> hits = searchResponse.hits();
        for (Hit<User> hit : hits.hits()) {
            System.out.println("user = " + hit.source().toString());
        }
        System.out.println("searchResponse.hits().total().value() = " + searchResponse.hits().total().value());

        transport.close();
        restClient.close();
    }
  • 分页查询
@Test
    public void pagingQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 分页查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test")
                        .query(q -> q.matchAll(m -> m))
                        .from(2)
                        .size(2)
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

分页查询就是在全量查询的基础上增加了从第几条开始,每页显示几条

  • 排序查询
    @Test
    public void sortQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 排序查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test")
                        .query(q -> q.matchAll(m -> m))
                        .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }
  • 条件查询
    @Test
    public void conditionQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 条件查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.matchAll(m -> m))
                        .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
                        .source(r -> r.filter(f -> f.includes("name", "age").excludes("")))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

includes是显示的字段,excludes是排除的字段文章来源地址https://www.toymoban.com/news/detail-847953.html

  • 组合查询
  @Test
    public void combinationQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 组合查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.bool(b -> b
                        .must(m -> m.match(u -> u.field("age").query(21)))
                        .must(m -> m.match(u -> u.field("sex").query("男")))
                        .mustNot(m -> m.match(u -> u.field("sex").query("女")))
                ))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

    @Test
    public void combinationQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 组合查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.bool(b -> b
                        .should(h -> h.match(u -> u.field("age").query(19)))
                        .should(h -> h.match(u -> u.field("sex").query("男")))
                ))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

到了这里,关于Elasticsearch8.x版本Java客户端Elasticsearch Java API Client中常用API练习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • ElasticSearch-学习笔记04【Java客户端操作索引库】

    ElasticSearch-学习笔记04【Java客户端操作索引库】

    Java后端-学习路线-笔记汇总表【黑马程序员】 ElasticSearch-学习笔记01【ElasticSearch基本介绍】 【day01】 ElasticSearch-学习笔记02【ElasticSearch索引库维护】 ElasticSearch-学习笔记03【ElasticSearch集群】 ElasticSearch-学习笔记04【Java客户端操作索引库】 【day02】 ElasticSearch-学习笔记05【Spri

    2023年04月09日
    浏览(11)
  • 干货 | Elasticsearch Java 客户端演进历史和选型指南

    干货 | Elasticsearch Java 客户端演进历史和选型指南

    Elasticsearch 官方提供了很多版本的 Java 客户端,包含但不限于: Transport 客户端 Java REST 客户端 Low Level REST 客户端 High Level REST 客户端 Java API 客户端 非官方的 Java 客户端,包含但不限于: Jest 客户端 BBoss 客户端 Spring Data Elasticsearch 客户端 ...... 写出来的就接近十款客户端! El

    2023年04月11日
    浏览(6)
  • Elasticsearch Java客户端和Spring data elasticsearch-Elasticsearch文章三

    Elasticsearch Java客户端和Spring data elasticsearch-Elasticsearch文章三

    https://www.elastic.co/cn/ 整合springboot看上一篇文章 一定要对应好版本,Elasticsearch 的不同版本变化是真大, https://docs.spring.io/spring-data/elasticsearch/docs/4.4.10/reference/html/ Springboot: 2.7.10 spring-data-elasticsearch: 4.4.10 spring-boot-starter-data-elasticsearch: 2.7.10 elasticsearch-java: 7.17.9 https://github.com/

    2024年02月14日
    浏览(15)
  • windows环境安装elasticsearch+kibana并完成JAVA客户端查询

    windows环境安装elasticsearch+kibana并完成JAVA客户端查询

    elasticsearch 官网下载比较慢,有时还打不开,可以通过https://elasticsearch.cn/download/下载,先找到对应的版本,最好使用迅雷下载,秒下的,我的下载速度可以达到40M/S 解压后点击 elasticsearch-7.10.0binelasticsearch.bat 运行成功后,输入http://120.0.0.1:9200,可以访问说明ES启动成功 点击

    2024年02月14日
    浏览(9)
  • [elastic 8.x]java客户端连接elasticsearch与操作索引与文档

    为了方便演示,我关闭了elasticsearch的安全验证,带安全验证的初始化方式将在最后专门介绍 其中,HotelDoc是一个实体类 带安全验证的连接有点复杂,将下列代码中CA证书的位置改为实际所在的位置就行了。 password为elastic的密码,可以在我的另一篇文章中查看密码的重置方式

    2024年04月11日
    浏览(14)
  • Elasticsearch:在 Java 客户端应用中管理索引 - Elastic Stack 8.x

    管理索引是客户端应用常用的一些动作,比如我们创建,删除,打开 及关闭索引等操作。在今天的文章中,我将描述如何在 Java 客户端应用中对索引进行管理。 我们需要阅读之前的文章 “Elasticsearch:在 Java 客户端中使用 truststore 来创建 HTTPS 连接”。在那篇文章中,我们详

    2023年04月09日
    浏览(7)
  • Java客户端调用elasticsearch进行深度分页查询 (search_after)

    Java客户端调用elasticsearch进行深度分页查询 (search_after)

    前言 这是我在这个网站整理的笔记,有错误的地方请指出,关注我,接下来还会持续更新。 作者:神的孩子都在歌唱 具体的Search_after解释,可以看我这篇文章 elasticsearch 深度分页查询 Search_after(图文教程) 参考:https://blog.csdn.net/qq_44056652/article/details/126341810 作者:神的孩子

    2024年03月22日
    浏览(5)
  • 【ElasticSearch】基于 Java 客户端 RestClient 实现对 ElasticSearch 索引库、文档的增删改查操作,以及文档的批量导入

    【ElasticSearch】基于 Java 客户端 RestClient 实现对 ElasticSearch 索引库、文档的增删改查操作,以及文档的批量导入

    ElasticSearch 官方提供了各种不同语言的客户端,用来操作 ES。这些客户端的本质就是组装 DSL 语句,通过 HTTP 请求发送给 ES 服务器。 官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/index.html。 在本文中,我们将着重介绍 ElasticSearch Java 客户端中的 RestClient,并演示如何

    2024年02月08日
    浏览(12)
  • 【ElasticSearch】使用 Java 客户端 RestClient 实现对文档的查询操作,以及对搜索结果的排序、分页、高亮处理

    【ElasticSearch】使用 Java 客户端 RestClient 实现对文档的查询操作,以及对搜索结果的排序、分页、高亮处理

    在 Elasticsearch 中,通过 RestAPI 进行 DSL 查询语句的构建通常是通过 HighLevelRestClient 中的 resource() 方法来实现的。该方法包含了查询、排序、分页、高亮等所有功能,为构建复杂的查询提供了便捷的接口。 RestAPI 中构建查询条件的核心部分是由一个名为 QueryBuilders 的工具类提供

    2024年01月16日
    浏览(15)
  • 【Elasticsearch学习笔记五】es常用的JAVA API、es整合SpringBoot项目中使用、利用JAVA代码操作es、RestHighLevelClient客户端对象

    目录 一、Maven项目集成Easticsearch 1)客户端对象 2)索引操作 3)文档操作 4)高级查询 二、springboot项目集成Spring Data操作Elasticsearch 1)pom文件 2)yaml 3)数据实体类 4)配置类 5)Dao数据访问对象 6)索引操作 7)文档操作 8)文档搜索 三、springboot项目集成bboss操作elasticsearch

    2023年04月09日
    浏览(9)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包