elk7.7.1【系列二】集成 Java High Level REST Client,並查詢es中所有索引

1、pom.xml中集成rest-high-level-client

<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>elasticsearch-rest-high-level-client</artifactId>
			<version>7.7.1</version>
			<exclusions>
				<exclusion>
					<groupId>org.elasticsearch</groupId>
					<artifactId>elasticsearch</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<version>7.7.1</version>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>elasticsearch-rest-client</artifactId>
			<version>7.7.1</version>
		</dependency>

2、java代碼

package com.ruoyi.project.log.controller;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.client.GetAliasesResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.cluster.metadata.AliasMetaData;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class t {

    RestHighLevelClient client = null;

    /**
     * 獲取api操作客戶端
     *
     * @return
     */
    public void getClient() {
        client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("192.168.81.129", 9200, "http")
        ));
    }

    /**
     * 關閉客戶端
     */
    public void closeClient() {
        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取所有es索引
     */
    public Set<String> getAllIndices() {
        try {
            getClient();
            GetAliasesRequest request = new GetAliasesRequest();
            GetAliasesResponse getAliasesResponse = client.indices().getAlias(request, RequestOptions.DEFAULT);
            Map<String, Set<AliasMetaData>> map = getAliasesResponse.getAliases();
            Set<String> indices = map.keySet();
            return indices;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeClient();
        }
        return new HashSet<>();
    }

    public static void main(String[] args) {
        t t = new t();
        System.out.println(t.getAllIndices());
    }
}

附Java High Level REST Client文檔地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章