Skip to content

Commit

Permalink
Merge pull request #15 from snakeye/master
Browse files Browse the repository at this point in the history
Added aggregations to response if requested
  • Loading branch information
vrcmarcos committed Mar 4, 2019
2 parents 3a31753 + 6861516 commit f068f52
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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

0 comments on commit f068f52

Please sign in to comment.