Skip to content

Commit

Permalink
Merge pull request #297 from algolia/feat/syno-rule-iterators
Browse files Browse the repository at this point in the history
feat: Iterators on synonyms and rules of an index
  • Loading branch information
LeoErcolanelli committed Oct 18, 2017
2 parents 7987851 + ee52e65 commit 32e82a5
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions algoliasearch/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,69 @@ def _load_next_page(self):
self.pos = 0
self.cursor = self.answer.get('cursor', None)

class SynonymIterator:
"""Iterator on the synonyms of an index"""

def __init__(self, index, hits_per_page=1000):
self.index = index
self.hits_per_page = hits_per_page
self.page = 0

def __iter__(self):
self._load_next_page()
return self

def __next__(self):
return self.next()

def next(self):
if self.pos >= len(self.response['hits']):
self._load_next_page()
if self.pos < len(self.response['hits']):
result = self.response['hits'][self.pos]
self.pos += 1
# Remove highlighting.
if '_highlightResult' in result: del result['_highlightResult']
return result
else:
raise StopIteration

def _load_next_page(self):
self.response = self.index.search_synonyms('', page=self.page, hits_per_page=self.hits_per_page)
self.page += 1
self.pos = 0

class RuleIterator:
"""Iterator on the rules of an index"""

def __init__(self, index, hits_per_page=1000):
self.index = index
self.hits_per_page = hits_per_page
self.page = 0

def __iter__(self):
self._load_next_page()
return self

def __next__(self):
return self.next()

def next(self):
if self.pos >= len(self.response['hits']):
self._load_next_page()
if self.pos < len(self.response['hits']):
result = self.response['hits'][self.pos]
self.pos += 1
# Remove highlighting.
if '_highlightResult' in result: del result['_highlightResult']
return result
else:
raise StopIteration

def _load_next_page(self):
self.response = self.index.search_rules('', page=self.page, hitsPerPage=self.hits_per_page)
self.page += 1
self.pos = 0

class Index(object):
"""
Expand Down

0 comments on commit 32e82a5

Please sign in to comment.