项目中使用es(二):使用RestHighLevelClient操作elasticsearch

这篇具有很好参考价值的文章主要介绍了项目中使用es(二):使用RestHighLevelClient操作elasticsearch。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

写在前面

之前写了有关elasticsearch的搭建和使用springboot操作elasticsearch,这次主要简单说下使用RestHighLevelClient工具包操作es。

搭建环境和选择合适的版本

环境还是以springboot2.7.12为基础搭建的,不过这不重要,因为这次想说的是RestHighLevelClient操作elasticsearch,RestHighLevelClient版本使用的是7.6.2,还需要引入elasticsearch客户端maven配置,版本也是7.6.2.
主要maven配置:

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.32</version>
        </dependency>

具体代码实现

1.首先是通过springboot实例化RestHighLevelClient对象

package com.es.demo.config;

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;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.uris}")
    private String urls;
    
    @Bean
    public RestHighLevelClient geClient() {
        RestHighLevelClient client = null;
        String[] split = urls.split(":");
        HttpHost httpHost = new HttpHost(split[0], Integer.parseInt(split[1]), "http");
        client = new RestHighLevelClient(RestClient.builder(httpHost));
        return client;
    }
}

2.RestHighLevelClient的简单例子,这里我就没有抽出来公共方法,只是简单的写了一下如何使用。
首先是接口

public interface ProductHighService {

    Boolean save(ProductInfo... productInfo);

    Boolean delete(Integer id);

    ProductInfo getById(Integer id);

    List<ProductInfo> getAll();

    List<ProductInfo> query(String keyword);
}

然后是实现

@Service
public class ProductHighServiceImpl implements ProductHighService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean save(ProductInfo... productInfo) {
//        IndexRequest request = new IndexRequest();
//        for (ProductInfo info : productInfo) {
//            request.index("product-info").id(String.valueOf(info.getId()));
//            request.source(XContentType.JSON, info);
//            try {
//                IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//                // 打印结果信息
//                System.out.println("_index: " + response.getIndex());
//                System.out.println("id: " + response.getId());
//                System.out.println("_result: " + response.getResult());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
        //循环插入/更新
//        UpdateRequest updateRequest = new UpdateRequest();
//        for (ProductInfo info : productInfo) {
//            updateRequest.index("product-info").id(String.valueOf(info.getId()));
//            updateRequest.doc(XContentType.JSON, info);
//            try {
//                UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
//                // 打印结果信息
//                System.out.println("_index: " + response.getIndex());
//                System.out.println("id: " + response.getId());
//                System.out.println("_result: " + response.getResult());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }

        //批量操作estHighLevelClient.bulk()可以包含新增,修改,删除
        BulkRequest request = new BulkRequest();
        Arrays.stream(productInfo).forEach(info -> {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("product-info").id(String.valueOf(info.getId()));
            try {
                //通过ObjectMapper将对象转成字符串再保存,如果不转的话存入的格式不是正常的json格式数据,不能转成对象
                ObjectMapper objectMapper = new ObjectMapper();
                String productJson = objectMapper.writeValueAsString(info);
                indexRequest.source(productJson, XContentType.JSON);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            request.add(indexRequest);
        });
        try {
            BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            System.out.println(response.status().getStatus());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public Boolean delete(Integer id) {
        DeleteRequest deleteRequest = new DeleteRequest().index("product-info").id(String.valueOf(id));
        try {
            DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            // 打印结果信息
            System.out.println("_index: " + response.getIndex());
            System.out.println("_id: " + response.getId());
            System.out.println("result: " + response.getResult());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public ProductInfo getById(Integer id) {
        GetRequest getRequest = new GetRequest().index("product-info").id(String.valueOf(id));
        try {
            GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            // 打印结果信息
            System.out.println("_index: " + response.getIndex());
            System.out.println("_type: " + response.getType());
            System.out.println("_id: " + response.getId());
            System.out.println("source: " + response.getSourceAsString());
            if (StringUtils.hasLength(response.getSourceAsString())) {
                return JSONObject.parseObject(response.getSourceAsString(), ProductInfo.class);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public List<ProductInfo> getAll() {
        SearchRequest request = new SearchRequest();
        request.indices("product-info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //restHighLevelClient在执行默认查询时返回条数都是10条,查询所有的时候要设置上size
        //lasticsearch exception [type=illegal_argument_exception, reason=Result window is too large, from + size must be less than or equal to: [10000] but was [1000000]
        //size不能设置查过10000条,
        searchSourceBuilder.size(1000);
        request.source(searchSourceBuilder);
        List<ProductInfo> result = new ArrayList<>();
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            response.getHits().forEach(e -> {
                ProductInfo productInfo = JSONObject.parseObject(e.getSourceAsString(), ProductInfo.class);
                result.add(productInfo);
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public List<ProductInfo> query(String keyword) {
        //https://blog.csdn.net/qq_38826019/article/details/121344376
        SearchRequest request = new SearchRequest();
        request.indices("product-info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("productName", keyword));
        searchSourceBuilder.query(QueryBuilders.matchQuery("description", keyword));
        //分页
//        searchSourceBuilder.from();
//        searchSourceBuilder.size()
        request.source(searchSourceBuilder);
        List<ProductInfo> result = new ArrayList<>();
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            response.getHits().forEach(e -> {
                ProductInfo productInfo = JSONObject.parseObject(e.getSourceAsString(), ProductInfo.class);
                result.add(productInfo);
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}

这里注意一点:restHighLevelClient在执行查询的时候默认返回10条,所以如果查询数量大于10条的话需要手动设置sizesearchSourceBuilder.size(1000),但是size的大小不能查过10000条,es有限制查询记录数不能超过10000,如果设置过大就会报错:elasticsearch exception [type=illegal_argument_exception, reason=Result window is too large, from + size must be less than or equal to: [10000] but was [1000000]

最后

别的的话好像没有遇到什么问题,因为我就是写了一个简单的demo测试一下
demo地址:https://gitee.com/wdvc/es-demo.git,有兴趣可以看下。文章来源地址https://www.toymoban.com/news/detail-629037.html

到了这里,关于项目中使用es(二):使用RestHighLevelClient操作elasticsearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • Elasticsearch-RestHighLevelClient基础操作

    该篇文章参考下面博主文章 Java中ElasticSearch的各种查询(普通,模糊,前缀,高亮,聚合,范围) 【es】java使用es中三种查询用法from size、search after、scroll 删除索引会把索引中已经创建好的数据也删除,就好像我们在mysql中删除库,会把库的数据也删除掉一样。 类似关闭数据

    2024年02月08日
    浏览(32)
  • ES聚合查询 基于RestHighLevelClient依赖 Java操作

    一、介绍 (偏自我理解)         1.ES聚合查询通用流程                 1.分组 ( 好比Mysql --- group by )                 2.组内聚合 也叫 组内指标( 好比Mysql --- SUM()、COUNT()、AVG()、MAX()、MIN() )         2.桶(我要是es开发者,我起名叫啥都行)                 1.满足特

    2024年02月06日
    浏览(37)
  • ElasticSearch系列 - SpringBoot整合ES:restHighLevelClient.count(countRequest, RequestOptions.DEFAULT)

    restHighLevelClient.count(countRequest, RequestOptions.DEFAULT) 是 Elasticsearch Java High Level REST Client 中用于执行计数请求的方法。 具体来说,它接受两个参数: countRequest:一个 CountRequest 对象,表示计数请求的参数,包括要计数的索引、查询条件等。 RequestOptions.DEFAULT:一个 RequestOptions 对象

    2024年02月08日
    浏览(47)
  • SpringBoot 实现 elasticsearch 索引操作(RestHighLevelClient 的应用)

    RestHighLevelClient 是 Elasticsearch 官方提供的Java高级客户端,用于与 Elasticsearch 集群进行交互和执行各种操作。 主要特点和功能如下 : 强类型 :RestHighLevelClient 提供了强类型的 API,可以在编码过程中获得更好的类型安全性和 IDE 支持。 兼容性 :RestHighLevelClient 是 Elasticsearch 官方

    2024年02月11日
    浏览(33)
  • SpringBoot 实现 elasticsearch 查询操作(RestHighLevelClient 的案例实战)

    上一节讲述了 SpringBoot 实现 elasticsearch 索引操作,这一章节讲述 SpringBoot 实现 elasticsearch 查询操作。 案例用到的索引库结构

    2024年02月11日
    浏览(35)
  • ES客户端RestHighLevelClient的使用

    默认情况下,ElasticSearch使用两个端口来监听外部TCP流量。 9200端口:用于所有通过HTTP协议进行的API调用。包括搜索、聚合、监控、以及其他任何使用HTTP协议的请求。所有的客户端库都会使用该端口与ElasticSearch进行交互。 9300端口:是一个自定义的二进制协议,用于集群中各

    2024年02月03日
    浏览(31)
  • Java使用Springboot集成Es官方推荐(RestHighLevelClient)

    SpringBoot集成ElasticSearch的四种方式(主要讲解ES官方推荐方式) TransportClient:这种方式即将弃用 官方将在8.0版本彻底去除 Data-Es:Spring提供的封装的方式,由于是Spring提供的,所以每个SpringBoot版本对应的ElasticSearch,具体这么个对应的版本,自己去官网看 ElasticSearch SQL:将Elasti

    2023年04月08日
    浏览(28)
  • Java 操作RestHighLevelClient基本使用

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

    2024年02月11日
    浏览(31)
  • SpringBoot+Elasticsearch使用resthighlevelclient对象删除指定的文档数据

    使用客户端删除 在 Kibana 中,你可以使用 Dev Tools 或者 Console 来执行 Elasticsearch 查询和删除操作。 ​ 以下是一个使用 Dev Tools 执行删除文档的示例: ​ 1.打开 Kibana,转到左侧导航栏的 “Dev Tools” 或者 “Console”。 ​ 2.在 Dev Tools 或者 Console 中输入如下删除请求: 请替换 /

    2024年01月23日
    浏览(39)
  • SpringBoot+Elasticsearch使用resthighlevelclient对象查询条件为“且+或”

    查询年龄为15或者16或者17或者18的且班级为1班的学生信息 首先,确保您的项目中包含了 Elasticsearch 的依赖: 然后,您可以创建一个包含查询逻辑的服务类。假设您有一个名为 StudentService 的服务类: 在上述代码中,您需要替换 your_index_name 为实际的 Elasticsearch 索引名称,并根

    2024年01月25日
    浏览(36)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包