【问题标题】:elasticsearch_dsl response multiple bucket aggregationselasticsearch_dsl 响应多桶聚合
【发布时间】:2018-10-02 22:36:11
【问题描述】:

找到这个关于如何使用 elasticsearch_dsl Generate multiple buckets in aggregation 构建嵌套聚合的线程

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

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

不起作用,要不然怎么获取num_servers或server_list中的内容?

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2015-11-11
      • 2012-05-23
      • 1970-01-01
      • 2021-06-06
      相关资源
      最近更新 更多