计算子聚合返回的存储桶

时间:2019-05-15 10:12:49

标签: elasticsearch

我需要从pipe aggregation返回的结果集中计算存储桶的数量。问题是我的查询在这里使用script selector

POST visitor_carts/_search
{
  "size": 0,
  "aggs": {
    "visitors": {
      "terms": {"field" : "visitor_id"},
      "aggs": {
        "one_purchase": {
          "bucket_selector": {
            "buckets_path": {
              "nb_purchases": "_count"
            },
            "script": "params.nb_purchases == 3"
          }
        }
      }
    }
  }
}

返回类似的内容:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 5,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "aggregations" : {
    "visitors" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "2",
          "doc_count" : 3
        },
        {
          "key" : "3",
          "doc_count" : 3
        }
      ]
    }
  }
}

buckets键下,我可以看到符合我条件的访客列表(由visitor_id标识的每个访客必须在visitor_carts索引中恰好有三个文档),但这不是非常有帮助,因为它应该可以处理成千上万的访客。我正在使用PHP处理结果,从理论上讲,它可以计算结果集,但是对于大量的访问者来说,这并不是最好的主意。有没有一种方法可以只输出doc_count_error_upper_boundsum_other_doc_count旁边的有效存储桶数?汇总统计信息中不包含bucket_count有点奇怪,因为它似乎非常有用。

或者这可以通过其他方式完成?这个问题是该问题的后续内容:Get user count that made a specific number of purchases

这是我的visitor_carts映射:

{
  "mapping": {
    "_doc": {
      "dynamic": "false",
      "properties": {
        "created_dt": {
          "type": "date",
          "format": "yyyy-MM-dd HH:mm:ss"
        },
        "order_id": {
          "type": "keyword"
        },
        "visitor_id": {
          "type": "keyword"
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Stats Bucket Aggregation来获取存储桶数。

下面是查询的样子。

汇总查询:

POST visitor_carts/_search
{
  "size": 0,
  "aggs": {
    "visitors": {
      "terms": {
        "field" : "visitor_id"
      },
      "aggs": {
        "one_purchase": {
          "bucket_selector": {
            "buckets_path": {
              "nb_purchases": "_count"
            },
            "script": "params.nb_purchases == 3"
          }
        }
      }
    },
    "mybucketcount":{
      "stats_bucket": {
        "buckets_path":"visitors._count"
      }
    }
  }
}

汇总结果:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 8,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "visitors": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "2",
          "doc_count": 3
        },
        {
          "key": "3",
          "doc_count": 3
        }
      ]
    },
    "mybucketcount": {
      "count": 2,              <---- This is the count you are looking for
      "min": 3,
      "max": 3,
      "avg": 3,
      "sum": 6
    }
  }
}

让我知道这是否有帮助!