Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import uuid
- ...
- def get_index_from_alias(alias, indices_client):
- if indices_client.exists(alias):
- return list(indices_client.get(alias).keys())[0]
- return None
- def recreate_index(model, indices_client):
- """Given a model create an index in elasticsearch,
- or recreate it if an alias to it already exists
- :param model: Model we are creating the index for
- :type model: Django Model
- """
- print('(Re)creating Index for {}'.format(model.es_index_alias))
- # Configuring the settings for the index that will be created. This can later be pushed to
- # the model incase there are more settings that we need to configure
- es_index_settings = {
- 'settings': {
- 'index': {
- 'number_of_replicas': model.es_number_of_replicas,
- 'number_of_shards': model.es_number_of_shards
- }
- }
- }
- # Get the existing index name from the alias
- existing_index = get_index_from_alias(model.es_index_alias, indices_client)
- if not existing_index:
- # If the index does not exist, then this is the first time an index is
- # created for this alias, add an alias in the settings from the beginning
- es_index_settings['aliases'] = {model.es_index_alias: {}}
- # Generate a new unique index name
- new_index = "{}_{}".format(model.es_index_alias, uuid.uuid4())
- while indices_client.exists(new_index):
- new_index = "{}_{}".format(model.es_index_alias, uuid.uuid4())
- # Create the new index with the settings defined above
- indices_client.create(index=new_index, body=es_index_settings)
- # Send the mapping defined for the new index
- indices_client.put_mapping(
- # The common consensus is to use _doc since it will be deprecated later
- doc_type='_doc',
- body=model.get_es_mapping(),
- index=new_index
- )
- return existing_index, new_index
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement