Search code examples
elasticsearchelasticsearch-dslelasticsearch-dsl-py

Scan result of a aggregation


I wanted to see how many unique link that a user has posted for every user. Here is what I have come up so far

s.aggs.bucket('user_term', A('terms', field='user__id')).metric('url_count', A('value_count', field='link'))

However, I have yet found a way to iterate through that result. Is there a way for this?


Solution

  • This will not give you a unique count, just a number of docs with a value for that field, you want to use a cardinality instead:

    s.aggs.bucket('users', 'terms', field='user.id').metric('url_count', 'cardinality', field='link')
    
    r = s.execute()
    
    for user in r.aggregations.users.buckets:
        print(f'User {user.key} posted {user.url_count.value} links')
    

    Hope this helps