作者注:本文系作者自己的理解.希望大家多多交流指正
官网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;