Elasticsearch java API增刪改查工具類

package com.util.logaggregation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hoperun.aimanager.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Elasticsearch 工具類
 *
 * @author: zhaohb
 * @create: 2019-10-16 17:39
 **/
@Slf4j
@Component
@PropertySource(value = "classpath:application.yml")
public class ElasticSearchUtils {
    private static String ip;
    private static int port;
    private static String protocol;
    private static RestClient restClient;

    @Value("${elasticsearch.ip}")
    private void setIp(String ip) {
        ElasticSearchUtils.ip = ip;
    }

    @Value("${elasticsearch.port}")
    private void setPort(int port) {
        ElasticSearchUtils.port = port;
    }

    @Value("${elasticsearch.protocol}")
    private void setProtocol(String protocol) {
        ElasticSearchUtils.protocol = protocol;
    }

    /**
     * 建立連接
     *
     * @return void
     * @Author zhaohb
     * @Date 2019/10/17 10:12
     * @Param []
     * @Thrown
     **/
    private static void getRestClient() {
        restClient = RestClient.builder(new HttpHost(ip, port, protocol)).build();
    }

    public static RestHighLevelClient getClientConnection() {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(ip, port, protocol)
                )
        );

        return client;
    }

    /**
     * cat api
     *
     * @return String
     * @Author zhaohb
     * @Date 2019/10/17 10:14
     * @Param []
     * @Thrown
     **/
    public static String catApi(String optional) {
        String method = "GET";
        String endpoint = optional == null ? "/_cat" : "/_cat/" + optional;
        Response response = null;
        getRestClient();
        try {
            response = restClient.performRequest(new Request(method, endpoint));
            log.info("catapi method excute success");
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("catapi method throw exceptions" + e.getMessage());
            return null;
        }
    }

    /**
     * 創建索引
     *
     * @return void
     * @Author zhaohb
     * @Date 2019/10/17 10:36
     * @Param [indexName]
     * @Thrown
     **/
    public static void createIndex(String indexName) {
        String method = "PUT";
        String endpoint = "/" + indexName;
        Request request = new Request(method, endpoint);
        Response response = null;
        getRestClient();
        try {
            response = restClient.performRequest(request);
            log.info(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("createIndex method throw exceptions" + e.getMessage());
        }
    }

    /**
     * 添加document json格式
     *
     * @return void
     * @Author zhaohb
     * @Date 2019/10/17 10:49
     * @Param [indexName, type, id, document]
     * @Thrown
     **/
    public static void createDocument(String indexName, String type, String id, String document) {
        String method = "POST";
        String endpoint = id == null ? "/" + indexName + "/" + type : "/" + indexName + "/" + type + "/" + id;
        HttpEntity entity = new NStringEntity(document, ContentType.APPLICATION_JSON);
        Request request = new Request(method, endpoint);
        request.setEntity(entity);
        getRestClient();
        try {
            Response response = restClient.performRequest(request);
            log.info(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("createDocument method throw exceptions" + e.getMessage());
        }
    }

    /**
     * 獲取文檔
     *
     * @return java.lang.String
     * @Author zhaohb
     * @Date 2019/10/17 11:48
     * @Param [indexName, type, id]
     * @Thrown
     **/
    public static String getDocument(String indexName, String type, String id) {
        String method = "GET";
        String endpoint = "/" + indexName + "/" + type + "/" + id;
        Response response = null;
        getRestClient();
        try {
            response = restClient.performRequest(new Request(method, endpoint));
            log.info("getDocument method execute success");
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("getDocument method throw exceptions" + e.getMessage());
        }
        return null;
    }

    /**
     * 根據索引、類型獲取文檔
     *
     * @return java.lang.String
     * @Author zhaohb
     * @Date 2019/10/16 13:58
     * @Param [indexName, type]
     * @Thrown
     **/
    public static String getDocuments(String indexName, String type) {
        String method = "GET";
        String endpoint = type == null ? "/" + indexName + "/_search" : "/" + indexName + "/" + type + "/_search";
        Response response = null;
        getRestClient();
        try {
            response = restClient.performRequest(new Request(method, endpoint));
            JSONObject result = JSON.parseObject(EntityUtils.toString(response.getEntity()));
            JSONObject hit = result.getJSONObject("hits");
            return JSON.toJSONString(hit);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("getDocument method throw exceptions" + e.getMessage());
        }
        return null;
    }

    /**
     * 分頁查詢、篩選、排序查詢
     *
     * @return java.lang.String
     * @Author zhaohb
     * @Date 2020/1/17 10:06
     * @Param [indexName, start, size, filtrate, sort]
     * @Thrown
     **/
    public static String paginationSearch(String indexName, int start, int size, String filterName,Object filterValue, String sort) {

        String result = "";
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        if (!StringUtils.isBlank(filterName)) {
            sourceBuilder.query(QueryBuilders.matchPhraseQuery(filterName, filterValue));
        }
        if (!StringUtils.isEmpty(sort)) {
            if (sort.indexOf("-") != 0) {
                sourceBuilder.sort(sort, SortOrder.ASC);
            } else {
                sourceBuilder.sort(sort, SortOrder.DESC);
            }
        }
        sourceBuilder.from(start);
        sourceBuilder.size(size);
        sourceBuilder.timeout(new TimeValue(1000));
        sourceBuilder.trackTotalHits(true);
        searchRequest.source(sourceBuilder);
        RestHighLevelClient client = getClientConnection();
        try {
            SearchResponse response = client.search(new SearchRequest(indexName)
                    .source(sourceBuilder), RequestOptions.DEFAULT);
            result = response.toString();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("paginationSearch method throw exceptions" + e.getMessage());
        }
        return result;
    }

}

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