Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import uuid
  2.  
  3.  
  4. ...
  5.  
  6.  
  7. def get_index_from_alias(alias, indices_client):
  8. if indices_client.exists(alias):
  9. return list(indices_client.get(alias).keys())[0]
  10. return None
  11.  
  12.  
  13. def recreate_index(model, indices_client):
  14. """Given a model create an index in elasticsearch,
  15. or recreate it if an alias to it already exists
  16.  
  17. :param model: Model we are creating the index for
  18. :type model: Django Model
  19. """
  20. print('(Re)creating Index for {}'.format(model.es_index_alias))
  21. # Configuring the settings for the index that will be created. This can later be pushed to
  22. # the model incase there are more settings that we need to configure
  23. es_index_settings = {
  24. 'settings': {
  25. 'index': {
  26. 'number_of_replicas': model.es_number_of_replicas,
  27. 'number_of_shards': model.es_number_of_shards
  28. }
  29. }
  30. }
  31.  
  32. # Get the existing index name from the alias
  33. existing_index = get_index_from_alias(model.es_index_alias, indices_client)
  34.  
  35. if not existing_index:
  36. # If the index does not exist, then this is the first time an index is
  37. # created for this alias, add an alias in the settings from the beginning
  38. es_index_settings['aliases'] = {model.es_index_alias: {}}
  39.  
  40. # Generate a new unique index name
  41. new_index = "{}_{}".format(model.es_index_alias, uuid.uuid4())
  42. while indices_client.exists(new_index):
  43. new_index = "{}_{}".format(model.es_index_alias, uuid.uuid4())
  44.  
  45. # Create the new index with the settings defined above
  46. indices_client.create(index=new_index, body=es_index_settings)
  47.  
  48. # Send the mapping defined for the new index
  49. indices_client.put_mapping(
  50. # The common consensus is to use _doc since it will be deprecated later
  51. doc_type='_doc',
  52. body=model.get_es_mapping(),
  53. index=new_index
  54. )
  55.  
  56. return existing_index, new_index
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement