如何在elasticsearch中进行范围聚合

l0oc07j2  于 2021-06-15  发布在  ElasticSearch
关注(0)|答案(1)|浏览(339)

按字段聚合时,请在此处输入图像描述 userguid ```
{
"_source": false,
"aggregations": {
"range_userGuid": {
"terms": {
"field": "userGuid"
}
}
}
}

我知道结果了

"aggregations" : {
"range_userGuid" : {
"doc_count_error_upper_bound" : 151,
"sum_other_doc_count" : 2424145,
"buckets" : [
{
"key" : 803100110976,
"doc_count" : 1
},
{
"key" : 813110447915,
"doc_count" : 10
},
{
"key" : 803100110306,
"doc_count" : 101
},
{
"key" : 2123312,
"doc_count" : 300
},
{
"key" : 3452342,
"doc_count" : 9999
},
]
}
}

现在我想从aggs结果中得到范围。例如(0-100),(100-1000),>1000,获取用户数。预期结果:

[
{
"from": 0,
"to": 100,
"count": 2 <---- 2 users, 803100110976 and 813110447915
},
{
"from": 100,
"to": "1000",
"count": 2 <---- 803100110306 and 2123312
},
{
"from": 1001,
"count": 1 <---- 3452342
}
]

aggs的bucket大小约为150000,如何编写这样的查询?
cwdobuhd

cwdobuhd1#

你可以用 range 聚合以实现您的期望:

POST /test/_search
{
   "size": 0,
   "aggs": {
      "range_userGuid": {
         "range": {
            "field": "userGuid",
            "ranges": [
               {
                  "from": 0,
                  "to": 100
               },
               {
                  "from": 100,
                  "to": 200
               },
               {
                  "from": 200,
                  "to": 1000
               },
               {
                  "from": 1000
               }
            ]
         }
      }
   }
}

更新:根据您的需要调整此答案:

POST index/_search
{
  "size": 0,
  "aggs": {
    "users_0_100": {
      "terms": {
        "field": "userGuid",
        "size": 1000
      },
      "aggs": {
        "0_100": {
          "bucket_selector": {
            "buckets_path": {
              "docCount": "_count"
            },
            "script": "params.docCount < 100"
          }
        }
      }
    },
    "users_100_200": {
      "terms": {
        "field": "userGuid",
        "size": 1000
      },
      "aggs": {
        "100_200": {
          "bucket_selector": {
            "buckets_path": {
              "docCount": "_count"
            },
            "script": "params.docCount >= 100 && params.docCount < 200"
          }
        }
      }
    },
    "users_200_1000": {
      "terms": {
        "field": "userGuid",
        "size": 1000
      },
      "aggs": {
        "200_1000": {
          "bucket_selector": {
            "buckets_path": {
              "docCount": "_count"
            },
            "script": "params.docCount >= 200 && params.docCount < 1000"
          }
        }
      }
    },
    "users_1000": {
      "terms": {
        "field": "userGuid",
        "size": 1000
      },
      "aggs": {
        "1000": {
          "bucket_selector": {
            "buckets_path": {
              "docCount": "_count"
            },
            "script": "params.docCount >= 1000"
          }
        }
      }
    }
  }
}

相关问题