其他分享
首页 > 其他分享> > ESClient

ESClient

作者:互联网

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

 

package com.joysuccess.dcim.alarm.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuccess.framework.common.utils.HelpUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.ParsedMin;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ParsedExtendedStats;
import org.elasticsearch.search.aggregations.metrics.sum.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;


public class ESClient {

    private static RestHighLevelClient client;

    public static RestHighLevelClient initClient() {
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("10.228.103.5", 9200, "http"),
                        new HttpHost("10.228.103.6", 9200, "http"),
                        new HttpHost("10.228.103.7", 9200, "http")
                )
        );
        return client;
    }

    public static void close() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Double getEsDataByTime(RestHighLevelClient client1, String indexName,  String[] pointCodeArr, String startTime, String endTime) throws IOException {
        Double sum = 0.0;
        if (indexExists(client1, indexName)) {
            //1.分页
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.timeout(new TimeValue(120000));
            // 设置排序规则
            sourceBuilder.sort("createDate", SortOrder.DESC);
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createDate").gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss");
            boolQueryBuilder.must(rangeQueryBuilder);
           // String[] pointCodeArr = pointCodes.split(",");
            for (String pointCode : pointCodeArr) {
                boolQueryBuilder.should(QueryBuilders.termQuery("pointCode", pointCode));
            }
            boolQueryBuilder.minimumShouldMatch(1);
            sourceBuilder.size(pointCodeArr.length);

            sourceBuilder.query(boolQueryBuilder);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(indexName).types("_doc");
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);
            SearchResponse searchResponse = client1.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHit =  searchResponse.getHits();
            for (SearchHit hit : searchHit) {
                String _source = hit.getSourceAsString();
                JSONObject jsonObject = JSONObject.parseObject(_source);
                String pointCode = jsonObject.getString("pointCode");
                String pointValues = jsonObject.getString("pointValue");
                if (HelpUtils.isNotEmpty(pointValues) && !"-9999".equals(pointValues)) {
                    sum = sum + Double.parseDouble(pointValues);
                }
                System.out.println("pointCode【 "+pointCode +" 】pointValues 【 "+pointValues+" 】");
            }
            close();
        }
        return sum;
    }

    public static SearchHits getEsDataPointByTime(String index,  String pointCode, String startTime, String endTime) throws IOException {
        if (indexExists(index)) {
            //1.分页
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //从第0个开始
            sourceBuilder.from(0);
            //相当于 limit
            sourceBuilder.size(1);
            // 设置排序规则--默认是命中分数最高者排前面
            // sourceBuilder.sort("releaseDate", SortOrder.DESC);
            sourceBuilder.sort("createDate", SortOrder.DESC);
            // 设置超时时间为2s
            sourceBuilder.timeout(new TimeValue(120000));
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            //文档内容匹配

            MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery("pointCode", pointCode);
            boolBuilder.must(matchQueryBuilder1);

            //时间范围查询
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createDate").gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss");
            boolBuilder.must(rangeQueryBuilder);
            sourceBuilder.query(boolBuilder);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(index).types("_doc");
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);
            SearchResponse searchResponse = initClient().search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();


            return hits;
        }
        return null;
    }


    /*
     * 查询某个时间范围的 某个字段的平均值
     */
    public static SearchHits getHisDataByTime(String index, String matchContent, String matchContentValue, String rangeQuery, String startTime, String endTime) throws IOException {
        SearchResponse searchResponse = new SearchResponse();
        if (indexExists(index)) {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //从第0个开始
            sourceBuilder.from(0);
            //相当于 limit
            sourceBuilder.size(8700);
            // 设置排序规则--默认是命中分数最高者排前面
            // sourceBuilder.sort("releaseDate", SortOrder.DESC);
            sourceBuilder.sort("createDate", SortOrder.DESC);
            // 设置超时时间为2s
            sourceBuilder.timeout(new TimeValue(10000));
            // 设置超时时间为2s
            sourceBuilder.timeout(new TimeValue(10000));
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            //文档内容匹配
            if (!"".equals(matchContent) && !"".equals(matchContentValue)) {
                MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery(matchContent, matchContentValue);
                boolBuilder.must(matchQueryBuilder1);
            }
            //时间范围查询
            if (!"".equals(rangeQuery) && !"".equals(startTime) && !"".equals(endTime)) {
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(rangeQuery).gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss");
                boolBuilder.must(rangeQueryBuilder);
            }

            sourceBuilder.query(boolBuilder);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(index).types("_doc");
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);

            // 5.查询
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        }
        //取出结果对象
        SearchHits hits = searchResponse.getHits();
        close();
        return hits;
    }


    /*
     * 查询某个时间范围的 某个字段的平均值
     */
    public static double getAvgByTime(String index, String matchContent, String matchContentValue, String rangeQuery, String startTime, String endTime) throws IOException {
        double data = 0.0;
        if (indexExists(index)) {
            //1.分页
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 设置超时时间为2s
            sourceBuilder.timeout(new TimeValue(10000));
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            //文档内容匹配
            if (!"".equals(matchContent) && !"".equals(matchContentValue)) {
                MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery(matchContent, matchContentValue);
                boolBuilder.must(matchQueryBuilder1);
            }
            //时间范围查询
            if (!"".equals(rangeQuery) && !"".equals(startTime) && !"".equals(endTime)) {
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(rangeQuery).gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss");
                boolBuilder.must(rangeQueryBuilder);
            }

            sourceBuilder.query(boolBuilder);
            AggregationBuilder aggregation = AggregationBuilders.avg("avgPointValue").field("pointValue");
            sourceBuilder.aggregation(aggregation);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(index).types("_doc");
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);
            long start = System.currentTimeMillis();
            // 5.查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            Avg avg = searchResponse.getAggregations().get("avgPointValue");
            data = avg.getValue();
        }
        return data;

    }

    public static double getTotalByTime(String index, String matchContent, String matchContentValue, String rangeQuery, String startTime, String endTime) throws IOException {
        double data = 0.0;
        if (indexExists(index)) {
            //1.分页
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 设置超时时间为2s
            sourceBuilder.timeout(new TimeValue(10000));
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            //文档内容匹配
            if (!"".equals(matchContent) && !"".equals(matchContentValue)) {
                MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery(matchContent, matchContentValue);
                boolBuilder.must(matchQueryBuilder1);
            }
            //时间范围查询
            if (!"".equals(rangeQuery) && !"".equals(startTime) && !"".equals(endTime)) {
                RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(rangeQuery).gte(startTime).lte(endTime).format("yyyy-MM-dd HH:mm:ss");
                boolBuilder.must(rangeQueryBuilder);
            }

            sourceBuilder.query(boolBuilder);
            AggregationBuilder aggregation = AggregationBuilders.sum("pointValues").field("pointValue");
            sourceBuilder.aggregation(aggregation);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(index).types("_doc");
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);
            long start = System.currentTimeMillis();
            // 5.查询
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            Sum sum = searchResponse.getAggregations().get("pointValues");
            data = sum.getValue();
        }
        return data;

    }

    /**
     * 获取某采集点某时间段内的聚合结果
     *
     * @param pointCode 采集点编码
     * @param startDate 起始时间 yyyy-MM-hh mm:hh:ss
     * @param endDate   起始时间 yyyy-MM-hh mm:hh:ss
     * @return JSONObject [{"date": "2021-11-1 10:10:00", "pointCode1": "123", "pointCode2": "222"...}]
     */
    public static JSONObject getPointValueExtendedStatsResult(RestHighLevelClient client1, String indexName, String typeName, String pointCode, String startDate, String endDate) throws IOException {
        JSONObject object = new JSONObject();
        if (indexExists(client1, indexName)) {
            //1.分页
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 设置超时时间为10s
            sourceBuilder.timeout(new TimeValue(10000));
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createDate").gt(startDate).lte(endDate));
            boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("pointCode", pointCode));
            TermsAggregationBuilder groupPointCode = AggregationBuilders.terms("groupPointCode").field("pointCode").size(1);
            ExtendedStatsAggregationBuilder extendedStatsAggregationBuilder = AggregationBuilders.extendedStats("extStatsPointValue").field("pointValue");
            groupPointCode.subAggregation(extendedStatsAggregationBuilder);
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.aggregation(groupPointCode);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(indexName).types(typeName);
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);
            // 5.查询
            SearchResponse searchResponse = client1.search(searchRequest, RequestOptions.DEFAULT);
            Terms terms = searchResponse.getAggregations().get("groupPointCode");
            if (null != terms && terms.getBuckets().size() > 0) {
                for (int i = 0; i < terms.getBuckets().size(); i++) {
                    Terms.Bucket bucket1 = terms.getBuckets().get(i);
                    ParsedExtendedStats parsedExtendedStats = bucket1.getAggregations().get("extStatsPointValue");
                    object.put("average", parsedExtendedStats.getAvg());
                    object.put("maximum", parsedExtendedStats.getMax());
                    object.put("minimum", parsedExtendedStats.getMin());
                    object.put("variance", parsedExtendedStats.getVariance());
                    object.put("standardDeviation", parsedExtendedStats.getStdDeviation());
                }
            }
        }
        return object;
    }

    /**
     * 获取数据查询表格数据
     *
     * @param pointCodes      采集点编码,逗号间隔
     * @param startDate       起始时间 yyyy-MM-hh mm:hh:ss
     * @param endDate         起始时间 yyyy-MM-hh mm:hh:ss
     * @param aggregationType 聚合方式 average 平均值 maximum 最大值  minimum 最小值 sum 求和
     * @param interval        颗粒度 minute 分钟 hour 小时 day 日 month 月"
     * @param allowEmpty      是否允许空值 即当前时间点无任何聚合结果的情况下,是否返回只有时间的对象,图表情况下需要
     * @return JSONArray [{"date": "2021-11-1 10:10:00", "pointCode1": "123", "pointCode2": "222"...}]
     */
    public static JSONArray getPointValueAggregationResult(RestHighLevelClient client1, String indexName, String typeName, String pointCodes, String startDate, String endDate, String aggregationType, String interval, boolean allowEmpty) throws IOException {
        JSONArray array = new JSONArray();
        if (indexExists(client1, indexName)) {
            //1.分页
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            // 设置超时时间为10s
            sourceBuilder.timeout(new TimeValue(10000));
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createDate").gt(startDate).lte(endDate));
            String[] pointCodeArr = pointCodes.split(",");
            for (String pointCode : pointCodeArr) {
                boolQueryBuilder.should(QueryBuilders.termQuery("pointCode", pointCode));
            }
            boolQueryBuilder.minimumShouldMatch(1);
            DateHistogramInterval dateHistogramInterval = DateHistogramInterval.HOUR;
            if (interval.equals("minute")) {
                dateHistogramInterval = DateHistogramInterval.MINUTE;
            } else if (interval.equals("day")) {
                dateHistogramInterval = DateHistogramInterval.DAY;
            } else if (interval.equals("month")) {
                dateHistogramInterval = DateHistogramInterval.MONTH;
            }

            AggregationBuilder aggregation = AggregationBuilders.dateHistogram("groupDate").field("createDate").minDocCount(0).dateHistogramInterval(dateHistogramInterval);
            TermsAggregationBuilder groupPointCode = AggregationBuilders.terms("groupPointCode").field("pointCode").size(pointCodeArr.length);
            if (aggregationType.equals("maximum")) {
                MaxAggregationBuilder maxAggregationBuilder = AggregationBuilders.max("statsPointValue").field("pointValue");
                groupPointCode.subAggregation(maxAggregationBuilder);
            } else if (aggregationType.equals("minimum")) {
                MinAggregationBuilder minAggregationBuilder = AggregationBuilders.min("statsPointValue").field("pointValue");
                groupPointCode.subAggregation(minAggregationBuilder);
            } else if (aggregationType.equals("sum")) {
                SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("statsPointValue").field("pointValue");
                groupPointCode.subAggregation(sumAggregationBuilder);
            } else {
                AvgAggregationBuilder avgPointValue = AggregationBuilders.avg("statsPointValue").field("pointValue");
                groupPointCode.subAggregation(avgPointValue);
            }
            aggregation.subAggregation(groupPointCode);
            sourceBuilder.query(boolQueryBuilder);
            sourceBuilder.aggregation(aggregation);
            // 4.创建并设置SearchRequest对象
            SearchRequest searchRequest = new SearchRequest();
            // 设置request要搜索的索引和类型
            searchRequest.indices(indexName).types(typeName);
            // 设置SearchSourceBuilder查询属性
            searchRequest.source(sourceBuilder);
            long start = System.currentTimeMillis();
            // 5.查询
            SearchResponse searchResponse = client1.search(searchRequest, RequestOptions.DEFAULT);
            ParsedDateHistogram parsedDateHistogram = searchResponse.getAggregations().get("groupDate");
            for (int i = 0; i < parsedDateHistogram.getBuckets().size(); i++) {
                Histogram.Bucket bucket = parsedDateHistogram.getBuckets().get(i);
                JSONObject jsonObject = new JSONObject();
                String key = bucket.getKeyAsString();
                Terms terms = bucket.getAggregations().get("groupPointCode");
                if (allowEmpty) {
                    jsonObject.put("date", key);
                }
                if (null != terms && terms.getBuckets().size() > 0) {
                    if (!allowEmpty) {
                        jsonObject.put("date", key);
                    }
                    for (int j = 0; j < terms.getBuckets().size(); j++) {
                        Terms.Bucket bucket1 = terms.getBuckets().get(j);
                        String pointCode = bucket1.getKeyAsString();
                        if (aggregationType.equals("maximum")) {
                            ParsedMax max = bucket1.getAggregations().get("statsPointValue");
                            jsonObject.put(pointCode, max.getValue());
                        } else if (aggregationType.equals("minimum")) {
                            ParsedMin min = bucket1.getAggregations().get("statsPointValue");
                            jsonObject.put(pointCode, min.getValue());
                        } else if (aggregationType.equals("sum")) {
                            ParsedSum sum = bucket1.getAggregations().get("statsPointValue");
                            jsonObject.put(pointCode, sum.getValue());
                        } else {
                            ParsedAvg avg = bucket1.getAggregations().get("statsPointValue");
                            jsonObject.put(pointCode, avg.getValue());
                        }
                    }
                }
                if (allowEmpty) {
                    array.add(jsonObject);
                }
                if (!allowEmpty && null != terms && terms.getBuckets().size() > 0) {
                    array.add(jsonObject);
                }
            }
        }
        return array;
    }

    /**
     * 判断es索引是否存在
     *
     * @param index
     * @return
     */
    public static Boolean indexExists(String index) {
        GetIndexRequest request = new GetIndexRequest().indices(index);
        Boolean flag = true;
        ;
        try {
            flag = client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            System.out.println("请检查es是否可以连通");
            e.printStackTrace();
            flag = false;
            return flag;
        }
        return flag;
    }

    /**
     * 判断es索引是否存在
     *
     * @param client 客户端
     * @param index  索引
     */
    public static Boolean indexExists(RestHighLevelClient client, String index) {
        GetIndexRequest request = new GetIndexRequest().indices(index);
        Boolean flag = true;
        ;
        try {
            flag = client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            System.out.println("请检查es是否可以连通");
            e.printStackTrace();
            flag = false;
            return flag;
        }
        return flag;
    }


//    public static void main(String[] arr) throws IOException {
//        RestHighLevelClient client =  new RestHighLevelClient(
//                RestClient.builder(
//                        new HttpHost("192.168.28.146", 9200, "http")
//                )
//        );
//        //1.分页
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        //从第0个开始
//        sourceBuilder.from(0);
//        //相当于 limit
//        sourceBuilder.size(8700);
//        // 设置排序规则--默认是命中分数最高者排前面
//        // sourceBuilder.sort("releaseDate", SortOrder.DESC);
//        sourceBuilder.sort("createDate", SortOrder.DESC);
//        // 设置超时时间为2s
//        sourceBuilder.timeout(new TimeValue(10000));
//        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
//        //文档内容匹配
//
//        MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery("pointCode", "1");
//        boolBuilder.must(matchQueryBuilder1);
//
//        //时间范围查询
//
//        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createDate").gte("2021-09-15 00:00:00").lte("2021-09-16 23:59:59").format("yyyy-MM-dd HH:mm:ss");
//        boolBuilder.must(rangeQueryBuilder);
//
//        sourceBuilder.query(boolBuilder);
//        // 4.创建并设置SearchRequest对象
//        SearchRequest searchRequest = new SearchRequest();
//        // 设置request要搜索的索引和类型
//        searchRequest.indices("2021-09").types("_doc");
//        // 设置SearchSourceBuilder查询属性
//        searchRequest.source(sourceBuilder);
//        long start = System.currentTimeMillis();
//        // 5.查询
//        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//        //取出结果对象
//        SearchHits hits = searchResponse.getHits();
//        long end = System.currentTimeMillis();
//        System.out.println("根据search方法查询,耗时:{} 秒"+ (end-start)/1000);
//        for(SearchHit hit:hits){
//            System.out.println(hit.getSourceAsString());
//        }
//    }


//    public static void main(String[] args) throws IOException {
//        client = initClient();
//        String pointCodes = "1.3.6.1.4.1.74226.3.3023.2.2.1.7.47.7,1.3.6.1.4.1.74226.3.3023.2.2.1.7.47.3,140019726,1.3.6.1.4.1.74226.3.3023.2.2.1.7.47.10,1.3.6.1.4.1.74226.3.3023.2.2.1.7.47.8";
//        if (indexExists(client, "dhjk")) {
//            //1.分页
//            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//            // 设置超时时间为10s
//            sourceBuilder.timeout(new TimeValue(10000));
//          //  sourceBuilder.size(1);
//            //从第0个开始
//          //  sourceBuilder.from(0);
//            //相当于 limit
//
//            // 设置排序规则--默认是命中分数最高者排前面
//            sourceBuilder.sort("createDate", SortOrder.DESC);
//            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//            boolQueryBuilder.must(QueryBuilders.rangeQuery("createDate").gt("2021-11-23 00:00:00").lte("2021-11-23 23:59:59"));
//            String[] pointCodeArr = pointCodes.split(",");
//            for (String pointCode : pointCodeArr) {
//                boolQueryBuilder.should(QueryBuilders.termQuery("pointCode", pointCode));
//            }
//            boolQueryBuilder.minimumShouldMatch(1);
//            sourceBuilder.size(pointCodeArr.length);
//
//            sourceBuilder.query(boolQueryBuilder);
//            // 4.创建并设置SearchRequest对象
//            SearchRequest searchRequest = new SearchRequest();
//            // 设置request要搜索的索引和类型
//            searchRequest.indices("dhjk").types("_doc");
//            // 设置SearchSourceBuilder查询属性
//            searchRequest.source(sourceBuilder);
//            long start = System.currentTimeMillis();
//            // 5.查询
//            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//            SearchHits searchHit =  searchResponse.getHits();
//            for (SearchHit hit : searchHit) {
//                String _source = hit.getSourceAsString();
//                JSONObject jsonObject = JSONObject.parseObject(_source);
//                String pointCode = jsonObject.getString("pointCode");
//                String pointValues = jsonObject.getString("pointValue");
//                System.out.println("pointCode【 "+pointCode +" 】pointValues 【 "+pointValues+" 】");
//            }
//
//        }
//
//
////        try {
////            JSONArray jsonArray = getPointValueAggregationResult(client, "dhjk", "_doc", "130003578,140004303", "2021-11-1 10:00:00", "2021-11-22 10:00:00", "average", "minute", false);
////            System.out.println(jsonArray);
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//    }


}

 

标签:String,org,sourceBuilder,new,elasticsearch,import,ESClient
来源: https://www.cnblogs.com/tonggc1668/p/15843909.html