【烦人的ElasticSearch】Es7 如何判断索引是否存在(Java版本)

2021/12/22 20:22:27

本文主要是介绍【烦人的ElasticSearch】Es7 如何判断索引是否存在(Java版本),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Es 搭建请自行寻找搭建方法

import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.RequestOptions;

public class EsServiceImpl implements EsService {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    
	public boolean checkEsIndex(String esIndex) throws Exception {
        GetIndexRequest request = new GetIndexRequest(esIndex);
        return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    }
}

附 RestHighLevelClient 配置

// 配置文件中新增配置
es:
  nodes: [ { "host": "127.0.0.1","port": 9200 } ]

// 新增 EsClientConfig 类
import com.bobft.fairy.vo.EsNodeVo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * Es 客户端配置
 *
 * @author hcf
 * Date: 2021/12/13 13:54
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "es")
public class EsClientConfig {

    private String clusterName;
    private List<EsNodeVo> nodes;
}


// 新增EsClient类
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.UnknownHostException;

/**
 * ES客户端
 *
 * @author hcf
 * @date 2021/12/17 13:55
 */
@Slf4j
@Component
public class EsClient {

    @Resource
    private EsClientConfig esClientConfig;

    /**
     * 获取Es客户端信息
     *
     * @return RestHighLevelClient
     * @throws IOException e
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() throws IOException {

        if (CollectionUtils.isEmpty(esClientConfig.getNodes())) {
            throw new UnknownHostException();
        }
        HttpHost[] httpHosts = esClientConfig.getNodes().stream().map(esNodeVo ->
                new HttpHost(esNodeVo.getHost(), esNodeVo.getPort(), "http")).toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts);
        builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(10000));
        return new RestHighLevelClient(builder);
    }
}


这篇关于【烦人的ElasticSearch】Es7 如何判断索引是否存在(Java版本)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程