提问者:小点点

带范围计数的Agg计数


我医生看起来像

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

我想拥有超过

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

谢谢你的帮助,


共1个答案

匿名用户

您需要使用术语聚合和bucket selector聚合,以根据用户的单据计数来分离用户ID

在下面的示例中,考虑5个“userid”:“33”文档、3个“userid”:“34”文档和1个“userid”:“35”文档。现在搜索查询将基于

  1. 单据计数小于或等于2
  2. 的用户计数
  3. 单据计数介于2和4之间的用户计数
  4. 单据计数大于或等于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
        }
      ]
    }
  }