es聚合-词条统计
es语句
---普通结构----"tags":{"type": "keyword","index": true},GET /knowledge_test/_search
{"size": 0,"aggs": {"tag_count": {"terms": {"field": "tags","size": 10000 // 设置足够 大的 size 值以包含所有可能的标签}}}
}--------------
nest结构:"inviteObjs": {"type": "nested","properties": {"email": {"type": "keyword","index": true},"userId": {"type": "keyword","index": true},"userName": {"type": "keyword","index": true}}},POST /knowledge/_search
{"size": 0,"query": {"term": {"authorId": "系统用户"}},"aggs": {"emails_count": {"nested": {"path": "inviteObjs"},"aggs": {"email_counts": {"terms": {"field": "inviteObjs.email","size": 10}}}}
对应api
----普通结构----
@Overridepublic List<String> queryTags(String type, Integer limit) {List<String> tags = new ArrayList<>();SearchRequest searchRequest = SearchRequest.of(s -> s.size(0).index(index).query(q -> q.term(t->t.field("type").value(type))).aggregations("tagsCount", a -> a.terms(t -> t.field("tags").size(limit))));SearchResponse<Object> response = EsSearchUtil.search(searchRequest, Object.class);Aggregate tagsCount = response.aggregations().get("tagsCount");if (tagsCount != null ){List<StringTermsBucket> hits = tagsCount.sterms().buckets().array();if (CollectionUtils.isEmpty(hits)){return tags;}for (StringTermsBucket hit : hits) {tags.add(hit.key().stringValue());}}return tags;}----nest----@Overridepublic List<InviteObjs> queryUsedEmail(Integer limit) {SearchRequest searchRequest = SearchRequest.of(s -> s.size(0).index(index).query(q -> q.term(t->t.field("authorId").value(UserUtil.getLoginUserId()))).aggregations("emailCount",a -> a.nested(n -> n.path("inviteObjs")).aggregations("email",at->at.terms(t->t.field("inviteObjs.email").size(limit)))));SearchResponse<Object> response = EsSearchUtil.search(searchRequest, Object.class);Aggregate emailCount = response.aggregations().get("emailCount");List<FieldValue> emails = new ArrayList<>();if (emailCount != null ){Aggregate emailAgg = emailCount.nested().aggregations().get("email");List<StringTermsBucket> hits = emailAgg.sterms().buckets().array();for (StringTermsBucket hit : hits) {String email = hit.key().stringValue();emails.add(FieldValue.of(email));}}
}
多层聚合统计
GET /knowledge/_search
{"size": 0,"range": {"timestamp": {"gte": "2015-01-01 00:00:00", // 设置开始时间"lte": "2025-12-31 23:59:59" // 设置结束时间}}},"aggs": {"by_type": {"terms": {"field": "type","size": 100 // 返回分类数量},"aggs": {"by_org": {"terms": {"field": "org","size": 50 // 返回分类数量}}}}}
}
对应代码
BoolQuery.Builder boolBuilder = new BoolQuery.Builder();boolBuilder.must(m->m.term(t->t.field(SearchConstants.TYPE).value(type)));boolBuilder.filter(m->m.range(r->r.field("timestamp").from(query.getStartTime()).to(query.getEndTime())));SearchRequest request = SearchRequest.of(s -> s.size(0).index(index).query(q -> q.bool(boolBuilder.build())).aggregations(firstCountName, a -> a.terms(t -> t.field(firstType).size(1000)).aggregations(secondCountName, a1 -> a1.terms(t -> t.field(secondType).size(1000)))));