作者注:本文系作者自己的理解.希望大家多多交流指正
官網java API
term是代表完全匹配,也就是精確查詢,搜索前不會再對搜索詞進行分詞,所以我們的搜索詞必須是文檔分詞集合中的一個
TermsBuilder:構造聚合函數
AggregationBuilders:創建聚合函數工具類
BoolQueryBuilder:拼裝連接(查詢)條件
QueryBuilders:簡單的靜態工廠”導入靜態”使用。主要作用是查詢條件(關系),如區間\精確\多值等條件
NativeSearchQueryBuilder:將連接條件和聚合函數等組合
SearchQuery:生成查詢
elasticsearchTemplate.query:進行查詢
Aggregations:Represents a set of computed addAggregation.代表一組添加聚合函數統計后的數據
Bucket:滿足某個條件(聚合)的文檔集合
使用示例:
public Map<String, Long> yananList(String str) {
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
long start=c.getTimeInMillis();
long end=System.currentTimeMillis();
Map<String, Long> map = new HashMap<String, Long>();
//子查詢
TermsBuilder tb= AggregationBuilders.terms("yanan7890")
.field("需要聚合的字段").order(Terms.Order.count(false)).size(int size(默認10)); //yanan7890是為聚合取的名稱,false降序,true升序
//查詢條件
BoolQueryBuilder bqb = QueryBuilders.boolQuery();
bqb.must(QueryBuilders.termQuery(string name, str);
bqb.must(QueryBuilders.rangeQuery("starttime").gt(start));// 大於
bqb.must(QueryBuilders.rangeQuery("endtime").lt(end));// 小於
//執行查詢條件
/**
*SearchType.COUNT,Only counts the results, will still execute facets and the like.
*EsIndexs.yanan7890指定索引
*/
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(bqb)
.withSearchType(SearchType.COUNT)
.withIndices(EsIndexs.yanan7890)
.addAggregation(tb).build();
// when
Aggregations aggregations = elasticsearchTemplate.query(searchQuery,
new ResultsExtractor<Aggregations>() {
@Override
public Aggregations extract(SearchResponse response) {
return response.getAggregations();
}
});
LongTerms modelTerms = (LongTerms) aggregations.asMap().get("yanan7890");//yanan7890是前面指定的聚合名稱.
Iterator<Bucket> modelBucketIt = modelTerms.getBuckets().iterator();
while (modelBucketIt.hasNext()) {
Bucket actiontypeBucket = modelBucketIt.next();
//actiontypeBucket.getKey().toString()聚合字段的相應名稱,actiontypeBucket.getDocCount()相應聚合結果
map.put(actiontypeBucket.getKey().toString(),
actiontypeBucket.getDocCount());
}
return map;
