Elasticsearch7 JavaHighLevelRESTClient+SpringBoot实现简单操作功能

随着Elasticsearch版本的迭代,早期的TransportClient不推荐使用,而推荐使用 Java High Level REST Client 并将在Elasticsearch 8.0中删除-------elasticsearch官方

好像spring data elasticsearch 低层也用到了TransportClient。

开始:

先建立一个springboot项目

引入依赖:版本要和你安装的elasticsearch版本一致,这里我用到了fastjson

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>

 注意:在pom.xml文件中<properties></properties>指明ES的版本避免报错

    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.5.1</elasticsearch.version>
    </properties>

然后再application.yml配置参数如下: 

如果没有配置elasticsearch密码验证就把username和password删除即可

spring:
  elasticsearch:
    rest:
      uris: ip1:9200,ip2:9200,ip3:9200  
      usernme: elastic       #如果你设置了基于x-pack的验证就要填写账号和密码
      password: 123456       #没有则不用配置
      connection-timeout: 100 #连接超时
      max-connection: 100  #最大连接数

新建一个EsClientConfiguration.java类,用于构建RestHighLevelClient客户端。

@Configuration
public class EsClientConfiguration {
    @Value("${spring.elasticsearch.rest.uris}")
    private String[] esUris;
    @Value("${spring.elasticsearch.rest.connection-timeout}")
    private  int connectTimeOut; // 连接超时时间
    @Value("${spring.elasticsearch.rest.max-connection}")
    private  int maxConnection; //最大连接数
    @Autowired
    private Environment environment;
    @Bean
    public RestHighLevelClient client() {
        String userName = environment.getProperty("spring.elasticsearch.rest.username");
        String password = environment.getProperty("spring.elasticsearch.rest.password");
        HttpHost[] httpHosts = new HttpHost[esUris.length];
        //将地址转换为http主机数组,未配置端口则采用默认9200端口,配置了端口则用配置的端口
        for (int i = 0; i < httpHosts.length; i++) {
            if (!StringUtils.isEmpty(esUris[i])) {
                if (esUris[i].contains(":")) {
                    String[] uris = esUris[i].split(":");
                    httpHosts[i] = new HttpHost(uris[0], Integer.parseInt(uris[1]), "http");
                } else {
                    httpHosts[i] = new HttpHost(esUris[i], 9200, "http");
                }
            }
        }
        //判断,如果未配置用户名,则进行无用户名密码连接,配置了用户名,则进行用户名密码连接
        if (StringUtils.isEmpty(userName)) {
            RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts));
            return client;
        } else {

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    //es账号密码
                    new UsernamePasswordCredentials(userName, password));
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(httpHosts)
                            .setHttpClientConfigCallback((httpClientBuilder) -> {
                                httpClientBuilder.setMaxConnTotal(maxConnection);
                                httpClientBuilder.disableAuthCaching();
                                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

                                return httpClientBuilder;
                            })
                            .setRequestConfigCallback(builder -> {
                                builder.setConnectTimeout(connectTimeOut);

                                return builder;
                            })
            );
            return client;
        }
    }
}
开始实现几个简单的功能
/**
 *实现了机个操作ES API
 * @param <T> 数据实体类
 */
@Component
public class EsUtils<T> {

    @Autowired
    private RestHighLevelClient client;
    /**
     * 判断索引是否存在
     * @param index
     * @return
     * @throws IOException
     */
    public boolean existsIndex(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }
    /**
     * 创建索引
     * @param index
     * @throws IOException
     */
    public boolean createIndex(String index) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse  =client.indices().create(request,RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

    /**
     * 删除索引
     * @param index
     * @return
     * @throws IOException
     */
    public boolean deleteIndex(String index) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        return response.isAcknowledged();

    }

    /**
     * 判断某索引下文档id是否存在
     * @param index
     * @param id
     * @return
     * @throws IOException
     */
    public boolean docExists(String index, String id) throws IOException {
        GetRequest getRequest = new GetRequest(index,id);
        //只判断索引是否存在不需要获取_source
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        return  exists;
    }

    /**
     * 添加文档记录
     * @param index
     * @param id
     * @param t 要添加的数据实体类
     * @return
     * @throws IOException
     */
    public boolean addDoc(String index,String id,T t) throws IOException {

        IndexRequest request = new IndexRequest(index);
        request.id(id);
        //timeout
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");
        request.source(JSON.toJSONString(t), XContentType.JSON);
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        RestStatus Status = indexResponse.status();
        return Status==RestStatus.OK||Status== RestStatus.CREATED;
    }

    /**
     * 根据id来获取记录
     * @param index
     * @param id
     * @return
     * @throws IOException
     */
    public GetResponse getDoc(String index,String id) throws IOException {
        GetRequest request = new GetRequest(index,id);
        GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
        return getResponse;
    }

    /**
     * 批量添加文档记录
     * 没有设置id ES会自动生成一个,如果要设置 IndexRequest的对象.id()即可
     * @param index
     * @param list
     * @return
     * @throws IOException
     */
    public boolean bulkAdd(String index, List<T> list) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        //timeout
        bulkRequest.timeout(TimeValue.timeValueMinutes(2));
        bulkRequest.timeout("2m");

        for (int i =0;i<list.size();i++){
            bulkRequest.add(new IndexRequest(index)
                    .source(JSON.toJSONString(list.get(i))));
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulkResponse.hasFailures();

    }

    /**
     * 批量删除和更新就不写了可根据上面几个方法来写
     */

    /**
     * 更新文档记录
     * @param index
     * @param id
     * @param t
     * @return
     * @throws IOException
     */
    public boolean updateDoc(String index,String id,T t) throws IOException {
        UpdateRequest request = new UpdateRequest(index,id);
        request.doc(JSON.toJSONString(t));
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");
        UpdateResponse updateResponse = client.update(
                request, RequestOptions.DEFAULT);
        return updateResponse.status()==RestStatus.OK;
    }


    /**
     * 删除文档记录
     * @param index
     * @param id
     * @return
     * @throws IOException
     */
    public boolean deleteDoc(String index,String id) throws IOException {
        DeleteRequest request = new DeleteRequest(index,id);
        //timeout
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");
        DeleteResponse deleteResponse = client.delete(
                request, RequestOptions.DEFAULT);

        return deleteResponse.status()== RestStatus.OK;
    }

    /**
     * 根据某字段来搜索
     * @param index
     * @param field
     * @param key 要收搜的关键字
     * @throws IOException
     */
    public void search(String index,String field ,String key,Integer from,Integer size) throws IOException {
        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery(field, key));
        //控制搜素
        sourceBuilder.from(from);
        sourceBuilder.size(size);
        //最大搜索时间。
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(searchResponse.getHits()));

    }

}

测试代码就不贴了,以上我都测试了没问题的。

  • 11
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值