Skip to content

Commit 1382c84

Browse files
committed
composite_agg example and tests
1 parent 511f1a9 commit 1382c84

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

examples/composite_agg.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from __future__ import print_function
2+
3+
from elasticsearch_dsl import connections, Search, A
4+
5+
def scan_aggs(search, source_aggs, inner_aggs={}, size=10):
6+
"""
7+
Helper function used to iterate over all possible bucket combinations of
8+
``source_aggs``, returning results of ``inner_aggs`` for each. Uses the
9+
``composite`` aggregation under the hood to perform this.
10+
"""
11+
def run_search(**kwargs):
12+
s = search[:0]
13+
s.aggs.bucket('comp', 'composite', sources=source_aggs, size=size, **kwargs)
14+
for agg_name, agg in inner_aggs.items():
15+
s.aggs['comp'][agg_name] = agg
16+
return s.execute()
17+
18+
response = run_search()
19+
while response.aggregations.comp.buckets:
20+
for b in response.aggregations.comp.buckets:
21+
yield b
22+
response = run_search(after=response.aggregations.comp.after_key)
23+
24+
25+
if __name__ == '__main__':
26+
connections.create_connection()
27+
s = Search(index='git')
28+
29+
for b in scan_aggs(s,
30+
{'files': A('terms', field='files')},
31+
{'first_seen': A('min', field='committed_date')}):
32+
print('File %s has been modified %d times, first seen at %s.' % (
33+
b.key.files, b.doc_count, b.first_seen.value_as_string
34+
))
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../../examples/composite_agg.py
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from elasticsearch_dsl import Search, A
2+
3+
from .composite_agg import scan_aggs
4+
5+
def test_scan_aggs_exhausts_all_files(data_client):
6+
s = Search(index='flat-git')
7+
key_aggs = {'files': A('terms', field='files')}
8+
file_list = list(scan_aggs(s, key_aggs))
9+
10+
assert len(file_list) == 26

0 commit comments

Comments
 (0)