//获取最近时间的一条数据
TopHitsAggregationBuilder maxTime = AggregationBuilders.topHits(maxField).sort(maxField, SortOrder.DESC).size(1);
        //根据groupField分组
        TermsAggregationBuilder termsAggregationBuilder =

//首先是分组                AggregationBuilders.terms(groupField).field(groupField).subAggregation(maxTime).
                        size(10000);

//获取最大的时间为了排序去做的聚合
        MaxAggregationBuilder field = AggregationBuilders.max("maxSort").field("msgSendTime");
        termsAggregationBuilder.subAggregation(field);

//这个地方的排序必须要用 一个number类型的聚合去排序
        FieldSortBuilder fieldSortBuilder=new FieldSortBuilder("maxSort").order(SortOrder.DESC);
        termsAggregationBuilder.subAggregation(new BucketSortPipelineAggregationBuilder("pageAndSort",
                Lists.newArrayList(fieldSortBuilder)).from(msgListReqDTO.getStartIndex()).size(msgListReqDTO.getPageSize()));
        //设置 searchQuery
        searchSourceBuilder.query(boolQueryBuilder).aggregation(termsAggregationBuilder).
                sort(maxField, SortOrder.DESC).size(0);

        request.searchType(SearchType.DEFAULT).source(searchSourceBuilder);
GET intelligent-core_message_es_index/_search
{
	"size": 0,
	"query": {
		"bool": {
			"must": [{
				"match": {
					"sessionStatus": {
						"query": "END"
					}
				}
			}, {
				"match": {
					"userId": {
						"query": "20220822151440349572086684327936"
					}
				}
			}],
			"must_not": [{
				"match": {
					"sendRole": {
						"query": "SYSTEM_VISITOR"
					}
				}
			}, {
				"terms": {
					"sendRole": ["SYSTEM_VISITOR", "SYSTEM_USER"]
				}
			}],
			"adjust_pure_negative": true,
			"boost": 1.0
		}
	},
	"sort": [{
		"msgSendTime": {
			"order": "desc"
		}
	}],
	"aggregations": {
		"visitorId": {
			"terms": {
				"field": "visitorId",
				"size": 10000,
				"order": [{
					"_count": "desc"
				}, {
					"_key": "asc"
				}]
			},
			"aggregations": {
				"msgSendTime": {
					"top_hits": {
						"from": 0,
						"size": 1,
						"sort": [{
							"msgSendTime": {
								"order": "desc"
							}
						}]
					}
				},
				"maxSort": {
					"max": {
						"field": "msgSendTime"
					}
				},
				"pageAndSort": {
					"bucket_sort": {
						"sort": [{
							"maxSort": {
								"order": "desc"
							}
						}],
						"from": 15,
						"size": 5
					}
				}
			}
		}
	}
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐