您好,登錄后才能下訂單哦!
/** * 從ES中查詢數據 * ES的時間如果不設置的話,默認是UTC時間,與北京時間相差8個小時,在查詢統計的時候,如果不做統計的話,數據肯定是不準確的。 * ES版本:6.4.1。使用的javaApi是 Elasearch High Level Rest Client6.4 * @param monthDate (patten:yyyy-MM) * @return List<SysCountResultVo> 統計結果。 */ public List<SysCountResultVo> queryOrderCountDataFromEs(String monthDate) { try { /** * 條件查詢(時間范圍) */ String startTime = DateUtil.getMonthFirstDay(DateUtil.dateStr2Date(monthDate + "-01", DateUtil.PATTERN_DTSHORTLINE)); String endTime = DateUtil.getMonthLastDay(DateUtil.dateStr2Date(monthDate + "-01", DateUtil.PATTERN_DTSHORTLINE)); Date s = DateUtil.dateStr2Date(startTime + " 00:00:00", DateUtil.PATTERN_SIMPLE); Date e = DateUtil.dateStr2Date(endTime + " 23:59:59", DateUtil.PATTERN_SIMPLE); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.must(QueryBuilders.rangeQuery("order_time").gte(s).lte(e)); searchSourceBuilder.query(boolQuery); /** * 分組聚合 */ TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("orderStatusCount").field("order_status"); aggregationBuilder.size(ESConstants.ES_AGG_SIZE); aggregationBuilder.collectMode(Aggregator.SubAggCollectionMode.BREADTH_FIRST); DateHistogramAggregationBuilder field = AggregationBuilders.dateHistogram("orderTime").field("order_time"); /* *時間統計的時候,注意時差問題。統計的時候,設置時區即可,不需要設置偏移量。 *offset偏移量這個參數,在某些時刻也是有用的,它可以自己定義一天的開始,比如設置從第一天的3點到第二天的3點為一天,默認都是從0點開始0點結束算做一天的 */ field.dateHistogramInterval(DateHistogramInterval.DAY).timeZone(DateTimeZone.getDefault());//.offset("+8h"); aggregationBuilder.subAggregation(field); searchSourceBuilder.aggregation(aggregationBuilder); SearchResponse response = client.searchDocument(ESConstants.ES_EC_ORDER_INDEX, ESConstants.ES_EC_ORDER_TYPE, searchSourceBuilder); //結果處理 Terms byPath = response.getAggregations().get("orderStatusCount"); List<? extends Terms.Bucket> buckets = byPath.getBuckets(); List<SysCountResultVo> resultVos = new ArrayList<>(); for (Terms.Bucket bucket : buckets) { Histogram agg = bucket.getAggregations().get("orderTime"); for (Histogram.Bucket entry : agg.getBuckets()) { SysCountResultVo sysCountVo = new SysCountResultVo(); sysCountVo.setLocalPath(bucket.getKeyAsString()); long t = ((DateTime)entry.getKey()).getMillis(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(t); sysCountVo.setDimension(DateUtil.date2DateStr(cal.getTime(),DateUtil.PATTERN_SIMPLE)); sysCountVo.setTimes(entry.getDocCount()); resultVos.add(sysCountVo); } } return resultVos; } catch (Exception e) { logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>從ES中查詢數據失敗"); e.printStackTrace(); return null; } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。