我们想要为 Elasticsearch 创建一个搜索查询
- 按
attestationIdentification
对文档进行分组 - 然后为每个组获取具有最大
attestationSituationNbr
的所有文档(每个组内可以有多个文档)。
问题
启动下面的查询时,我会获取每个 attestationIdentification
的存储桶,其中 attestationIdentification
的最大值位于 theMax
中。
但是,可以立即拿到文件吗?喜欢某种 top_hits
吗?或者我真的必须使用这些结果启动另一个搜索吗?
另外,是否可以使用 NEST.ElasticSearch 来做到这一点?
简单示例数据:
{
"attestationIdentification" : 1,
"attestationSituationNbr" : 20
},
{
"attestationIdentification" : 1,
"attestationSituationNbr" : 21
},
{
"attestationIdentification" : 2,
"attestationSituationNbr" : 30
}
我的查询
{
"aggs": {
"yourGroup": {
"terms": {
"field": "attestationIdentification",
"size": 10
},
"aggs": {
"theMax": {
"max": {
"field": "attestationSituationNbr"
}
}
}
}
}
}
结果
结果是每个组的最大值,但是,我想获取具有该最大值的文档:
...
"aggregations": {
"yourGroup": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 1,
"doc_count": 4,
"theMax": { "value": 21 }
},
{
"key": 2,
"doc_count": 2,
"theMax": { "value": 30 }
}
...
最佳答案
使用top_hits
,例如:
{
"size": 0,
"aggs": {
"yourGroup": {
"terms": {
"field": "attestationIdentification",
"size": 10
},
"aggs": {
"theMax": {
"top_hits": {
"size": "1",
"sort": {
"attestationSituationNbr": {
"order": "desc"
}
}
}
}
}
}
}
}
关于ElasticSearch获取group by后最大值的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37165741/