elasticsearch 查询近24小时数据 仅需24个点
时间: 2023-06-23 13:46:09 浏览: 237
您好,如果您想要查询 Elasticsearch 中近24小时数据,可以使用 Elasticsearch 的时间范围查询,然后再通过聚合计算出24个点的数据。
以下是一个示例代码,假设我们有一个名为 `logs` 的索引,其中包含 `timestamp` 和 `value` 两个字段:
```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.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class ElasticsearchQuery {
public static void main(String[] args) throws IOException {
// 创建 Elasticsearch 客户端
RestHighLevelClient client = createClient();
// 查询范围为近24小时
Instant now = Instant.now();
Instant twentyFourHoursAgo = now.minus(24, ChronoUnit.HOURS);
// 构建查询
SearchRequest searchRequest = new SearchRequest("logs");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.rangeQuery("timestamp")
.gte(twentyFourHoursAgo.toEpochMilli())
.lte(now.toEpochMilli()));
searchSourceBuilder.sort(SortBuilders.fieldSort("timestamp").order(SortOrder.ASC));
searchRequest.source(searchSourceBuilder);
// 构建聚合,将结果分成24个点,每个点的时间间隔为1小时
searchSourceBuilder.aggregation(AggregationBuilders
.dateHistogram("hourly_avg")
.field("timestamp")
.dateHistogramInterval(DateHistogramInterval.HOUR)
.minDocCount(1)
.subAggregation(AggregationBuilders.avg("avg_value").field("value")));
// 执行查询
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 解析结果
List<Double> hourlyAverages = new ArrayList<>();
for (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket bucket :
searchResponse.getAggregations().get("hourly_avg").getBuckets()) {
Avg avg = bucket.getAggregations().get("avg_value");
double value = avg.getValue();
hourlyAverages.add(value);
}
System.out.println(hourlyAverages);
// 关闭客户端
client.close();
}
private static RestHighLevelClient createClient() {
// 创建 Elasticsearch 客户端
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")
)
);
}
}
```
在这个示例中,我们首先计算出当前时间和24小时前的时间,然后使用范围查询来筛选出这个时间范围内的数据。然后,我们使用 Elasticsearch 的时间直方图(`date_histogram`)聚合来将结果分成24个点,每个点的时间间隔为1小时。在每个点上,我们使用平均值聚合来计算该点的平均值。最后,我们将每个点的平均值存储在一个列表中,并输出结果。
希望这可以帮助您。如果您有任何其他问题,请随时问我。
阅读全文