我正在使用复合词和术语聚合来基于给定字段获得分组结果。我还使用基数聚合来获取聚合存储桶的总数。
下面是我正在发送的请求查询,以获取相应的响应:
请求:
"aggs": {
"myfield_comp_agg": {
"aggs": {
"myfield": {
"aggs": {
"myfield_tophits": {
"top_hits": {
"size": 1
}
}
},
"terms": {
"field": "myfield",
"size": 10
}
}
},
"composite": {
"after": {
"myfield_comp_terms_agg": ""
},
"sources": [
{
"myfield_comp_terms_agg": {
"terms": {
"field": "myfield"
}
}
}
]
}
},
"Count_agg": {
"cardinality": {
"field": "myfield"
}
}
}
Response:
{
...,
"aggregations" : {
"Count_agg" : {
"value" : 33
},
"myfield_comp_agg" : {
"after_key" : {
"myfield_comp_terms_agg" : "value10"
},
"buckets" : [
{
"key" : {
"DocId_comp_terms_agg" : "value1"
},
"doc_count" : 1,
"DocId" : {...}
},
{...},
{...},
{...}
]
}
}
}
我使用Kibana检查查询,对我来说很好用。
但是,我不确定如何在我的NEST对象语法中使用此基数聚合器。
这是我的代码:
var termsAggregation = new TermsAggregation(GetTermsAggregationName(aggregationField)) {
Field = aggregationField,
Size = takeCount
};
var topHitsAggregation = new TopHitsAggregation(GetTopHitsAggregationName(aggregationField)) {
Size = aggregationFieldCount
};
var termsAggregationContainer = new AggregationContainer {
Terms = termsAggregation,
Aggregations = topHitsAggregation
};
var subAggregations = new Dictionary<string, IAggregationContainer>() {
{ aggregationField, termsAggregationContainer}
};
var compositeKey = new Dictionary<string, object>() {
{ GetCompositeTermsAggregationName(aggregationField), aggregationSkipValue }
};
var termsSource = new TermsCompositeAggregationSource(GetCompositeTermsAggregationName(aggregationField)) {
Field = aggregationField
};
var compositeAggregation = new CompositeAggregation(GetCompositeAggregationName(aggregationField)) {
After = new CompositeKey(compositeKey),
Sources = new List<TermsCompositeAggregationSource> { termsSource },
Aggregations = subAggregations
};
var searchRequest = new SearchRequest(request.IndexName)
{
From = request.SkipCount,
Size = request.TakeCount
};
searchRequest.Aggregations = compositeAggregation;
ElasticSearchClient.Search<T>(searchRequest);
非常感谢您的帮助。
Russ在评论中发布的答案。
查看客户端的写作汇总文档;它对更简洁的对象初始化器语法提供了一些建议,例如使用AggregationDictionary和&& ing聚合来组合它们。
这是与请求查询匹配的示例
var client = new ElasticClient();
AggregationDictionary aggs = new CompositeAggregation("myfield_comp_agg")
{
After = new CompositeKey(new Dictionary<string, object>
{
{ "myfield_comp_terms_agg", string.Empty }
}),
Sources = new ICompositeAggregationSource[]
{
new TermsCompositeAggregationSource("myfield_comp_terms_agg")
{
Field = "myfield"
}
},
Aggregations = new TermsAggregation("myfield")
{
Field = "myfield",
Size = 10,
Aggregations = new TopHitsAggregation("myfield_tophits")
{
Size = 1
}
}
} && new CardinalityAggregation("Count_agg", "myfield");
var searchRequest = new SearchRequest("my_index")
{
Aggregations = aggs
};
var searchResponse = client.Search<object>(searchRequest);
感谢您的帮助。效果很好。