Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added aggregations to response if requested #15

Merged
merged 7 commits into from
Mar 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion elasticmock/fake_elasticsearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

from elasticmock.utilities import get_random_id, get_random_scroll_id


PY3 = sys.version_info[0] == 3
if PY3:
unicode = str
Expand Down Expand Up @@ -185,6 +184,20 @@ def search(self, index=None, doc_type=None, body=None, params=None):
match['_score'] = 1.0
hits.append(match)

# build aggregations
if body is not None and 'aggs' in body:
aggregations = {}

for aggregation, definition in body['aggs'].items():
aggregations[aggregation] = {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}

if aggregations:
result['aggregations'] = aggregations

if 'scroll' in params:
result['_scroll_id'] = str(get_random_scroll_id())
params['size'] = int(params.get('size') if 'size' in params else 10)
Expand All @@ -198,6 +211,7 @@ def search(self, index=None, doc_type=None, body=None, params=None):
hits = hits[params.get('from'):params.get('from') + params.get('size')]

result['hits']['hits'] = hits

return result

@query_params('scroll')
Expand Down
8 changes: 8 additions & 0 deletions tests/test_elasticmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,14 @@ def test_doc_type_can_be_list(self):
result = self.es.search(doc_type=doc_types[:2])
self.assertEqual(count_per_doc_type * 2, result.get('hits').get('total'))

def test_usage_of_aggregations(self):
self.es.index(index='index', doc_type='document', body={'genre': 'rock'})

body = {"aggs": {"genres": {"terms": {"field": "genre"}}}}
result = self.es.search(index='index', body=body)

self.assertTrue('aggregations' in result)

def test_search_with_scroll_param(self):
for _ in range(100):
self.es.index(index='groups', doc_type='groups', body={'budget': 1000})
Expand Down