From b70823f2aaf1a33802bf654cb6e3c17b96dd25eb Mon Sep 17 00:00:00 2001
From: Karl Hobley <karlhobley10@gmail.com>
Date: Thu, 17 Dec 2015 15:50:07 +0000
Subject: [PATCH] refactor(search/elastic): cleanup AtomicRebuilder.finish()
 method

---
 .../wagtailsearch/backends/elasticsearch.py   | 28 +++++++++++--------
 1 file changed, 16 insertions(+), 12 deletions(-)

diff --git a/wagtail/wagtailsearch/backends/elasticsearch.py b/wagtail/wagtailsearch/backends/elasticsearch.py
index 4f301904b2..8f1c28c3ff 100644
--- a/wagtail/wagtailsearch/backends/elasticsearch.py
+++ b/wagtail/wagtailsearch/backends/elasticsearch.py
@@ -574,19 +574,11 @@ class ElasticSearchAtomicIndexRebuilder(ElasticSearchIndexRebuilder):
     def finish(self):
         self.index.refresh()
 
-        # Create the alias if it doesnt exist yet
-        if not self.alias.is_alias():
-            # Make sure there isn't currently an index that clashes with alias
-            # This can happen when the atomic rebuilder is first enabled
-            self.alias.delete()
+        if self.alias.is_alias():
+            # Update existing alias, then delete the old index
 
-            # Create the alias
-            self.index.put_alias(self.alias.name)
-
-        else:
-            # Alias already exists, update it and delete old index
-
-            # Find index that alias currently points to, so we can delete it later
+            # Find index that alias currently points to, we'll delete it after
+            # updating the alias
             old_index = self.alias.aliased_indices()
 
             # Update alias to point to new index
@@ -598,6 +590,18 @@ class ElasticSearchAtomicIndexRebuilder(ElasticSearchIndexRebuilder):
                 if index.name != self.index.name:
                     index.delete()
 
+        else:
+            # self.alias doesn't currently refer to an alias in Elasticsearch.
+            # This means that either nothing exists in ES with that name or
+            # there is currently an index with the that name
+
+            # Run delete on the alias, just in case it is currently an index.
+            # This happens on the first rebuild after switching ATOMIC_REBUILD on
+            self.alias.delete()
+
+            # Create the alias
+            self.index.put_alias(self.alias.name)
+
 
 class ElasticSearch(BaseSearch):
     index_class = ElasticSearchIndex