首页 > 解决方案 > 弹性搜索中按字段值数据聚合

问题描述

我有以下数据集,我希望根据状态进行聚合。不确定如何将状态值与拒绝或成功进行比较并获取结果计数。

{
    "took": 4,
    "timed_out": false,
    "_shards": {
        "total": 3,
        "successful": 3,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 2874,
        "max_score": 1,
        "hits": [
            {
                "_index": "testfiles",
                "_type": "testfiles",
                "_id": "testfile.one",
                "_score": 1,
                "_source": {
                    "businessDate": 20171013,
                    "status": "Success"
                }
            },
            {
                "_index": "testfiles",
                "_type": "testfiles",
                "_id": "testfile.two",
                "_score": 1,
                "_source": {
                    "businessDate": 20171013,
                    "status": "Success"
                }
            },
            {
                "_index": "testfiles",
                "_type": "testfiles",
                "_id": "testfile.three",
                "_score": 1,
                "_source": {
                    "businessDate": 20171013,
                    "status": "Rejected"
                }
            },
            {
                "_index": "testfiles",
                "_type": "testfiles",
                "_id": "testfile.four",
                "_score": 1,
                "_source": {
                    "businessDate": 20171013,
                    "status": "Rejected"
                }
            }
        ]
    }
}

有人可以帮助如何在弹性搜索聚合中实现这一点。

预期的响应如下

"aggregations": {
        "success_records": 2,
        "rejected_records": 2
    }

标签: elasticsearchaggregation

解决方案


假设statusfield 是 type text,您需要将其更新为具有聚合所需类型的多字段。keyword然后使用查询:

GET my_index/_search
{
  "size": 0,
  "aggs": {
    "statuses": {
      "terms": {
        "field": "status.raw"
      }
  }
}

如果您已经有statusaskeyword字段,则在上述查询中更改status.raw为。status


推荐阅读