This code snippet demonstrates how to build an Elasticsearch query using a range query builder to filter results based on time ranges.

The code checks if the latestTsFrom and latestTsTo parameters are not blank. If both are not blank, it converts them to timestamps using the DateUtil.FetchTimestamp method. It then defines a rangeQueryBuilder based on the value of enumerate:

  • enumerate == 1: Filters based on DeviceCurrentAlarm.LATEST_TS
  • enumerate == 2: Filters based on DeviceHistoryAlarm.CLEAR_TS
  • enumerate == 3: Filters based on DeviceScreenedAlarm.LATEST_TS and also adds a condition to include results from the past month.

The rangeQueryBuilder is then applied to the boolQueryBuilder using boolQueryBuilder.filter(rangeQueryBuilder) or boolQueryBuilder.must(rangeQueryBuilder) depending on the case. The code uses rangeQueryBuilder.gte(latestTsFromLong).lte(latestTsToLong) to filter results within the specified time range.

The simplified code uses a switch statement to efficiently determine the target field for the range query. It also consolidates the setting of the upper bound for the range query (System.currentTimeMillis()) and the application of the time range conditions to the boolQueryBuilder.

Simplified code:

if (StringUtils.isNotBlank(latestTsFrom) && StringUtils.isNotBlank(latestTsTo)) {
    Long latestTsFromLong = DateUtil.FetchTimestamp(latestTsFrom);
    Long latestTsToLong = DateUtil.FetchTimestamp(latestTsTo);
    RangeQueryBuilder rangeQueryBuilder = null;
    switch (enumerate) {
        case 1:
            rangeQueryBuilder = QueryBuilders.rangeQuery(DeviceCurrentAlarm.LATEST_TS);
            break;
        case 2:
            rangeQueryBuilder = QueryBuilders.rangeQuery(DeviceHistoryAlarm.CLEAR_TS);
            break;
        case 3:
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            long timestamp = cal.getTimeInMillis();
            rangeQueryBuilder = QueryBuilders.rangeQuery(DeviceScreenedAlarm.LATEST_TS).gte(timestamp);
            break;
    }
    if (rangeQueryBuilder != null) {
        rangeQueryBuilder.lte(System.currentTimeMillis());
        boolQueryBuilder.filter(rangeQueryBuilder.gte(latestTsFromLong).lte(latestTsToLong));
    }
}

This code provides a robust method for filtering Elasticsearch data based on time ranges, offering flexibility through the enumerate parameter and allowing for easy adaptation to different data models and time-based conditions.

Elasticsearch Query Builder with Time Range Filters

原文地址: http://www.cveoy.top/t/topic/oneA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录