java在BoolQueryBuilder构建rangeQueryBuilder查询一个月内的数据再构建子查询查询这个月内的任意时间段数据
以下是一个示例代码,假设要查询字段名为"date"的日期字段,查询一个月内的数据,并且再构建子查询查询这个月内的任意时间段数据:
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Example {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 构建查询范围
LocalDateTime oneMonthAgo = now.minusMonths(1);
String format = "yyyy-MM-dd'T'HH:mm:ss.SSS";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
String from = oneMonthAgo.format(formatter);
String to = now.format(formatter);
// 构建range查询
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("date").from(from).to(to);
// 构建子查询
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(rangeQuery);
boolQuery.must(QueryBuilders.rangeQuery("date").from("2021-05-01T00:00:00.000").to("2021-05-15T23:59:59.999"));
// 输出查询语句
System.out.println(boolQuery.toString());
}
}
在上述代码中,首先获取当前时间,然后构建一个月前和当前时间的范围,用于构建range查询,查询字段为"date"的日期字段。接着,构建一个bool查询,将range查询作为must条件,并且再添加一个子查询,查询字段为"date"的日期字段,在5月1日到5月15日之间的任意时间段内的数据。最后,输出查询语句,可以看到构建出来的查询语句包含了所有的条件
原文地址: http://www.cveoy.top/t/topic/fHJY 著作权归作者所有。请勿转载和采集!