Skip to content

Commit 32e82a5

Browse files
Merge pull request #297 from algolia/feat/syno-rule-iterators
feat: Iterators on synonyms and rules of an index
2 parents 7987851 + ee52e65 commit 32e82a5

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

algoliasearch/index.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,69 @@ def _load_next_page(self):
6969
self.pos = 0
7070
self.cursor = self.answer.get('cursor', None)
7171

72+
class SynonymIterator:
73+
"""Iterator on the synonyms of an index"""
74+
75+
def __init__(self, index, hits_per_page=1000):
76+
self.index = index
77+
self.hits_per_page = hits_per_page
78+
self.page = 0
79+
80+
def __iter__(self):
81+
self._load_next_page()
82+
return self
83+
84+
def __next__(self):
85+
return self.next()
86+
87+
def next(self):
88+
if self.pos >= len(self.response['hits']):
89+
self._load_next_page()
90+
if self.pos < len(self.response['hits']):
91+
result = self.response['hits'][self.pos]
92+
self.pos += 1
93+
# Remove highlighting.
94+
if '_highlightResult' in result: del result['_highlightResult']
95+
return result
96+
else:
97+
raise StopIteration
98+
99+
def _load_next_page(self):
100+
self.response = self.index.search_synonyms('', page=self.page, hits_per_page=self.hits_per_page)
101+
self.page += 1
102+
self.pos = 0
103+
104+
class RuleIterator:
105+
"""Iterator on the rules of an index"""
106+
107+
def __init__(self, index, hits_per_page=1000):
108+
self.index = index
109+
self.hits_per_page = hits_per_page
110+
self.page = 0
111+
112+
def __iter__(self):
113+
self._load_next_page()
114+
return self
115+
116+
def __next__(self):
117+
return self.next()
118+
119+
def next(self):
120+
if self.pos >= len(self.response['hits']):
121+
self._load_next_page()
122+
if self.pos < len(self.response['hits']):
123+
result = self.response['hits'][self.pos]
124+
self.pos += 1
125+
# Remove highlighting.
126+
if '_highlightResult' in result: del result['_highlightResult']
127+
return result
128+
else:
129+
raise StopIteration
130+
131+
def _load_next_page(self):
132+
self.response = self.index.search_rules('', page=self.page, hitsPerPage=self.hits_per_page)
133+
self.page += 1
134+
self.pos = 0
72135

73136
class Index(object):
74137
"""

0 commit comments

Comments
 (0)