Skip to content

Commit 36ec42f

Browse files
committed
Test for index existence before creation
Note that also when the index is an alias index_exists will be true.
1 parent 1fe0464 commit 36ec42f

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

annotator/elasticsearch.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -76,27 +76,24 @@ def create_models(self, models):
7676
mappings = _compile_mappings(models)
7777
analysis = _compile_analysis(models)
7878

79-
# If it does not yet exist, simply create the index
79+
# Test for index existence while also checking if connection works
8080
try:
81-
response = self.conn.indices.create(self.index, ignore=400, body={
82-
'mappings': mappings,
83-
'settings': {'analysis': analysis},
84-
})
85-
return
81+
index_exists = self.conn.indices.exists(self.index)
8682
except elasticsearch.exceptions.ConnectionError as e:
8783
msg = ('Can not access ElasticSearch at {0}! '
8884
'Check to ensure it is running.').format(self.host)
8985
raise elasticsearch.exceptions.ConnectionError('N/A', msg, e)
9086

91-
# Bad request (400) is ignored above, to prevent warnings in the log
92-
# when the index already exists, but the failure could be for other
93-
# reasons. If so, raise the error here.
94-
if 'error' in response and 'IndexAlreadyExists' not in response['error']:
95-
raise elasticsearch.exceptions.RequestError(400, response['error'])
96-
97-
# Update the mappings of the existing index
98-
self._update_analysis(analysis)
99-
self._update_mappings(mappings)
87+
if not index_exists:
88+
# If index does not yet exist, simply create the index
89+
self.conn.indices.create(self.index, body={
90+
'mappings': mappings,
91+
'settings': {'analysis': analysis},
92+
})
93+
else:
94+
# Otherwise, update its settings and mappings
95+
self._update_analysis(analysis)
96+
self._update_mappings(mappings)
10097

10198
def _update_analysis(self, analysis):
10299
"""Update analyzers and filters"""

0 commit comments

Comments
 (0)