elasticsearch_dsl response multiple bucket aggregations

2.1k Views Asked by At

found this thread on how to frame nested aggregations using elasticsearch_dsl Generate multiple buckets in aggregation

can someone show how to iterate through the response to get the second bucket results?

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

does not work, how else to get to the content in num_servers or server_list?

1

There are 1 best solutions below

0
Ryan Widmaier On BEST ANSWER

You need two loops if you want to loop through an second level aggregation. Here is an example assuming 'label' and 'number' fields in your index:

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)

Which would print something like this:

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