【烦人的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);
    }
}
上一篇:SOLID设计原则


下一篇:js(es7-es10)特性