Skip to content

Instantly share code, notes, and snippets.

@djamelz
Created October 12, 2015 21:09
Show Gist options
  • Save djamelz/59ebc8cc342a6ece1040 to your computer and use it in GitHub Desktop.
Save djamelz/59ebc8cc342a6ece1040 to your computer and use it in GitHub Desktop.
Elasticsearch Alias switching in python => restore the new one, close the latest and delete the olders (based on name versioning index_name_xxx, index_name_xxy for index name and index_name for alias)
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts=['es-host:9200'], timeout=600) #long timeout for the restore operation
snapshotName='index_name_20151012140502'
alias = es.indices.get_alias('index_name').keys()[0] if es.indices.exists_alias(name='index_name') else ''
indices = filter(lambda x: x.startswith('index_name'), es.indices.get_aliases())
indices.sort()
print 'restore repository'
es.snapshot.restore(repository='repository_name', snapshot=snapshotName, body ='{ "ignore_unavailable": "true", "include_global_state": false}', wait_for_completion=True)
if (len(alias) > 1):
print 'delete alias from index ' + alias
es.indices.delete_alias(index=alias, name='index_name')
if (len(indices) > 0):
toClose = indices.pop()
print toClose +' will be closed'
es.indices.close(index=toClose)
for index in indices:
print index +' will be deleted'
es.indices.delete(index=index)
es.indices.refresh(index='index_name')
print 'Done ! Here is Status'
print es.indices.status('index_name')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment