当前位置:   article > 正文

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

resthighlevel

写在前面

之前写了有关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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

具体代码实现

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

然后是实现

@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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145

这里注意一点: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,有兴趣可以看下。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/68595
推荐阅读
相关标签
  

闽ICP备14008679号