java调用es 根据时间区间查询索引
时间: 2023-08-11 10:12:44 浏览: 106
可以通过使用 Java API 调用 Elasticsearch 的查询接口来实现根据时间区间查询索引。以下是一个示例代码:
```java
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class EsQuery {
private static final String INDEX_NAME = "your_index_name";
private static final String DATE_FIELD = "your_date_field";
private RestHighLevelClient client;
public EsQuery(RestHighLevelClient client) {
this.client = client;
}
public void queryByTimeRange(LocalDateTime startTime, LocalDateTime endTime) throws IOException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("UTC"));
String startStr = formatter.format(startTime);
String endStr = formatter.format(endTime);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.rangeQuery(DATE_FIELD).gte(startStr).lte(endStr));
sourceBuilder.sort(SortBuilders.fieldSort(DATE_FIELD).order(SortOrder.DESC));
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理查询结果
}
}
```
在以上代码中,我们使用了 Elasticsearch 的 Range Query 进行时间区间查询,同时使用了 Sort 进行结果排序。注意,在进行时间字符串格式化时,我们要使用 UTC 时区。
阅读全文