ES快速开发,ElasticsearchRestTemplate基本使用以及ELK快速部署
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
@Service
public class ElasticsearchService {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public void searchWithAggregations() {
// 创建查询
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery()) // 匹配所有文档
.addAggregation(AggregationBuilders.avg("averagePrice").field("price")) // 计算价格的平均值
.addAggregation(AggregationBuilders.sum("totalRevenue").field("revenue")); // 计算收入总和
// 执行查询
AggregatedPage<Item> page = (AggregatedPage<Item>) elasticsearchRestTemplate.queryForPage(queryBuilder.build(), Item.class);
// 获取聚合结果
Avg averagePrice = page.getAggregations().get("averagePrice");
Sum totalRevenue = page.getAggregations().get("totalRevenue");
// 输出聚合结果
System.out.println("平均价格: " + averagePrice.getValue());
System.out.println("总收入: " + totalRevenue.getValue());
}
}
这段代码展示了如何使用ElasticsearchRestTemplate
来执行带有聚合查询的搜索操作。它构建了一个查询并添加了计算平均价格和收入总和的聚合。然后执行查询并输出聚合结果。这是一个简化的例子,实际应用中可能需要更复杂的查询和聚合逻辑。
评论已关闭