首页 > 解决方案 > 聚合计数和范围计数

问题描述

我的医生看起来像

{
      "path": "/foo/bar",
      "userId" : "33",
}

我想拥有超过

100 个文档 50 到 100 个文档 少于 100 个文档 我尝试使用不同的聚合,但我不知道如何根据另一个聚合的计数进行范围聚合

谢谢你的帮助,

标签: jqueryelasticsearchaggregation

解决方案


您需要将术语聚合存储桶选择器聚合一起使用,以根据其文档计数来隔离 UserId

在下面的示例中,考虑 的 5"UserId":"33"个文档、“UserId”的 3 个文档:“34”和 的 1 个文档"UserId":"35"。现在搜索查询将根据 UserId 隔离

  1. 文档计数小于或等于 2 的用户计数
  2. 文档数在 2 到 4 之间的用户数
  3. 文档计数大于或等于 4 的用户计数

添加带有索引数据、搜索查询和搜索结果的工作示例

指数数据:

{
      "path": "/foo/bar",
      "userId" : "34"
}
{
      "path": "/foo/bar",
      "userId" : "34"
}
{
      "path": "/foo/bar",
      "userId" : "34"
}
{
      "path": "/foo/bar",
      "userId" : "33"
}
{
      "path": "/foo/bar",
      "userId" : "33"
}
{
      "path": "/foo/bar",
      "userId" : "33"
}
{
      "path": "/foo/bar",
      "userId" : "33"
}
{
      "path": "/foo/bar",
      "userId" : "33"
}
{
      "path": "/foo/bar",
      "userId" : "35"
}

搜索查询:

{
  "size": 0,
  "aggs": {
    "userId_lessThanEqualTo2": {
      "terms": {
        "field": "userId.keyword"
      },
      "aggs": {
        "less_than_2": {
          "bucket_selector": {
            "buckets_path": {
              "the_doc_count": "_count"
            },
            "script": "params.the_doc_count < 2"
          }
        }
      }
    },
    "userId_btw2-4": {
      "terms": {
        "field": "userId.keyword"
      },
      "aggs": {
        "less_than_4": {
          "bucket_selector": {
            "buckets_path": {
              "the_doc_count": "_count"
            },
            "script": "params.the_doc_count >= 2 && params.the_doc_count < 4"
          }
        }
      }
    },
    "userId_greaterThanEqualTo4": {
      "terms": {
        "field": "userId.keyword"
      },
      "aggs": {
        "greater_than_4": {
          "bucket_selector": {
            "buckets_path": {
              "the_doc_count": "_count"
            },
            "script": "params.the_doc_count >= 4"
          }
        }
      }
    }
  }
}

搜索结果:

 "aggregations": {
    "userId_btw2-4": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "34",
          "doc_count": 3
        }
      ]
    },
    "userId_greaterThanEqualTo4": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "33",
          "doc_count": 5
        }
      ]
    },
    "userId_lessThanEqualTo2": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "35",
          "doc_count": 1
        }
      ]
    }
  }

推荐阅读