elasticsearch_dsl响应多个存储桶聚合

时间:2018-10-02 14:00:11

标签: elasticsearch elasticsearch-dsl elasticsearch-dsl-py

找到了该线程,了解如何使用elasticsearch_dsl Generate multiple buckets in aggregation

构建嵌套聚合

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

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

不起作用,如何获取num_servers或server_list中的内容?

1 个答案:

答案 0 :(得分:1)

如果要循环进行第二级聚合,则需要两个循环。这是一个假设您的索引中包含“标签”和“数字”字段的示例:

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="stackoverflow")
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