微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【烦人的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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐