elasticsearch_dsl 响应多桶聚合

elasticsearch_dsl response multiple bucket aggregations

找到有关如何使用 elasticsearch_dsl Generate multiple buckets in aggregation

构建嵌套聚合的线程

有人可以展示如何遍历响应以获得第二个存储桶结果吗?

for i in s.aggregations.clients.buckets.num_servers.buckets:

不起作用,还有什么方法可以获取 num_servers 或 server_list 中的内容?

如果要遍历二级聚合,则需要两个循环。这是一个示例,假设索引中有 'label' 和 'number' 字段:

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, A

client = Elasticsearch()

# Build a two level aggregation
my_agg = A('terms', field='label')
my_agg.bucket('number', A('terms', field='number'))

# Build and submit the query
s = Search(using=client, index="Whosebug")
s.aggs.bucket('label', my_agg)

response = s.execute()

# Loop through the first level of the aggregation
for label_bucket in response.aggregations.label.buckets:
    print "Label: {}, {}".format(label_bucket.key, label_bucket.doc_count)

    # Loop through the 2nd level of the aggregation
    for number_bucket in label_bucket.number.buckets:
        print "  Number: {}, {}".format(number_bucket.key, number_bucket.doc_count)

这将打印如下内容:

Label: A, 3
  Number: 2, 2
  Number: 1, 1
Label: B, 3
  Number: 3, 2
  Number: 1, 1