Elasticsearch聚合最大值

时间:2016-09-07 11:56:53

标签: elasticsearch

{
"aggs":{
    "nest_exams":{
        "nested":{
            "path": "exams"
        },
        "aggs":{
            "exams":{
                "filter" : { 
                    "term": {
                        "exams.exam_id": 96690
                    } 
                },
                "aggs":{
                    "nested_attempts":{
                        "nested":{
                            "path": "exams.attempts"
                        },
                        "aggs":{
                            "user_attempts":{
                                "terms":{
                                    "field": "exams.attempts.user_id",
                                    "size": 0
                                },
                                "aggs":{
                                    "max_score":{
                                        "max":{
                                            "field": "exams.attempts.order_score"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }        
}

您好,我有这个聚合查询。问题是,即使我可以找到每个用户的max_score,我也无法聚合到最大聚合器以找到这个最佳分数的日期。

尝试使用user_id,order_score,date_start

1 个答案:

答案 0 :(得分:1)

另一种方法是不运行max指标子聚合,而是top_hits而是按降序max_score排序,以便您可以检索该文档的date_start

{
  "aggs": {
    "nest_exams": {
      "nested": {
        "path": "exams"
      },
      "aggs": {
        "exams": {
          "filter": {
            "term": {
              "exams.exam_id": 96690
            }
          },
          "aggs": {
            "nested_attempts": {
              "nested": {
                "path": "exams.attempts"
              },
              "aggs": {
                "user_attempts": {
                  "terms": {
                    "field": "exams.attempts.user_id",
                    "size": 0
                  },
                  "aggs": {
                    "max_score": {
                      "top_hits": {
                        "sort": {
                          "exams.attempts.order_score": "desc"
                        },
                        "size": 1,
                        "_source": [
                          "date_start"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}