SpringBoot—Get the ES index name range according to the start time and end time

Follow wx:CodingTechWork

need

  According to the start time field of ES, query the index name range. The premise is that the index name is also named according to the year and month, such ases_log_data_m202304

template

@Slf4j
public class ESUtils{
    
    

    private Integer defaultSearchMonth = 6;
    /**
     * 根据起始时间和终止时间获取索引名称范围
     *
     * @param indexNamePrefix 索引前缀
     * @param beginTime       起始时间
     * @param endTime         终止时间
     * @return
     */
    public static List<String> queryEsIndexNameRange(String indexNamePrefix, LocalDateTime beginTime, LocalDateTime endTime) {
    
    
        //构建日期字符串列表  yyyyMM
        List<String> indexNameRangeList = new ArrayList<>();
        //设定了起止时间
        if (ObjectUtil.isNotEmpty(beginTime) && ObjectUtil.isNotEmpty(endTime)) {
    
    
            //若起始时间在终止时间之后,返回空
            if (beginTime.isAfter(endTime)) {
    
    
                return new ArrayList<>();
            }
            //循环处理 条件:起始时间在终止时间之前
            while (beginTime.isBefore(endTime)) {
    
    
                //添加起始日期
                indexNameRangeList.add(indexNamePrefix + DateTimeFormatter.ofPattern("yyyyMM").format(beginTime));
                //自增1个月
                beginTime = beginTime.plusMonths(1);
            }
            //考虑2023-02-01 00:00:00  2023-03-03 00:00:00时间范围的查询
            if (!indexNameRangeList.contains(indexNamePrefix + DateTimeFormatter.ofPattern("yyyyMM").format(endTime))) {
    
    
                //添加终止日期
                indexNameRangeList.add(indexNamePrefix + DateTimeFormatter.ofPattern("yyyyMM").format(endTime));
            }
        } else {
    
    
            //未设定起止时间,默认返回几个月
            LocalDateTime nowTime = LocalDateTime.now();
            //循环处理 条件:起始时间在终止时间之前的默认月数
            for (int i = 0; i < defaultSearchMonth; i++) {
    
    
                indexNameRangeList.add(indexNamePrefix + DateTimeFormatter.ofPattern("yyyyMM").format(nowTime));
                //自减月份
                nowTime = nowTime.minusMonths(1);
            }
        }
        log.info("es query indexNameRangeList: {}", indexNameRangeList);
        //返回索引范围list
        return indexNameRangeList;
    }
}

example

 //索引名称查询列表
List<String> indexNameList = ESUtils.getIndexNameRange("es_log_data_m,LocalDateTime.now(), LocalDateTime.now());
//构建es请求
SearchRequest.Builder builder = new SearchRequest.Builder();
//es query
Query.Builder builder = new Query.Builder();
BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();
builder.bool(boolQueryBuilder.build());
Query.Builder builderId = new Query.Builder();
builderId.term(new TermQuery.Builder().field("testId").value(10000L).build());
boolQueryBuilder.must(builderId.build());
//忽略索引不存在的情况
builder.index(indexNameList).query(builder.build()).ignoreUnavailable(true);

Guess you like

Origin blog.csdn.net/Andya_net/article/details/129937020