在 Elasticsearch 中获取值的百分比

Get Percentage of Values in Elasticsearch

我有一些测试文档看起来像

"hits": {
        ...
            "_source": {
               "student": "DTWjkg",
               "name": "My Name",
               "grade": "A"
            ...
               "student": "ggddee",
               "name": "My Name2",
               "grade": "B"
            ...
               "student": "ggddee",
               "name": "My Name3",
               "grade": "A"

我想得到成绩为 B 的学生所占的百分比,假设只有 3 名学生,结果将是“33%”。

我如何在 Elasticsearch 中执行此操作?

到目前为止我有这个聚合,我觉得它很接近:

"aggs": {
    "gradeBPercent": {
        "terms": {
            "field" : "grade",
            "script" : "_value == 'B'"
        }
    }
}

这个returns:

"aggregations": {
      "gradeBPercent": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "false",
               "doc_count": 2
            },
            {
               "key": "true",
               "doc_count": 1
            }
         ]
      }
   }

我不一定要寻找确切的答案,也许我可以找到我可以找到的术语和关键字 google。我已经阅读了 elasticsearch 文档,但没有找到任何有用的信息。

首先,您不需要用于此聚合的脚本。如果您想将结果限制为 `value == 'B' 的每个人,那么您应该使用过滤器而不是脚本来做到这一点。

ElasticSearch 不会 return 为您提供准确的百分比,但您可以使用 TERMS AGGREGATION.

的结果轻松计算出该百分比

示例:

GET devdev/audittrail/_search
{
  "size": 0,
  "aggs": {
    "a1": {
      "terms": {
        "field": "uIDRequestID"
      }
    }
  }
}

那个returns:

{
  "took": 12,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 25083,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "a1": {
      "doc_count_error_upper_bound": 9,
      "sum_other_doc_count": 1300,
      "buckets": [
        {
          "key": 556,
          "doc_count": 34
        },
        {
          "key": 393,
          "doc_count": 28
        },
        {
          "key": 528,
          "doc_count": 15
        }
      ]
    }
  }
}

那 return 是什么意思?

  • hits.total 字段是与您的查询匹配的记录总数。
  • doc_count 告诉您每个桶中有多少项目。

所以对于我这里的示例:我可以说键“556”出现在 25083 个文档中的 34 个中,因此它的百分比为 (34 / 25083) * 100