Guest User

Untitled

a guest
Jul 31st, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. import os
  2. import logging
  3.  
  4. from pymongo import ASCENDING, TEXT
  5. from pymongo import MongoClient, IndexModel, ASCENDING, DESCENDING
  6.  
  7.  
  8. class InL:
  9. def __init__(self, coll, ind, unique=False, name=None):
  10. self.collection = coll
  11.  
  12. if name is None:
  13. index = IndexModel(ind, unique=unique)
  14. else:
  15. index = IndexModel(ind, unique=unique, name=name)
  16. self.index = [index]
  17.  
  18.  
  19. class CreateIndex:
  20. def set_all_index(self):
  21. self.all_index = {}
  22. for coll in self.data_base.collection_names():
  23. self.all_index[coll] = {i: True for i in self.data_base[coll].index_information() if i[0] != '_'}
  24.  
  25. def __init__(self, host, username, password, db_name, index_list):
  26. self.index_list = index_list
  27.  
  28. mongodb_client = MongoClient(host=host, username=username, password=password)
  29. self.data_base = mongodb_client[db_name]
  30.  
  31. self.all_index = None
  32. self.set_all_index()
  33.  
  34. self.logging = logging.getLogger('mg_create_index')
  35.  
  36. def update_index_status(self, collection, index_name):
  37. if self.all_index.get(collection, {}).get(index_name):
  38. self.all_index[collection][index_name] = False
  39. self.logging.info('Update index (coll, index): {}, {}, ok'.format(collection, index_name))
  40. else:
  41. self.logging.info('Create new index (coll, index): {}, {}, ok'.format(collection, index_name))
  42.  
  43. def create_index(self, index_list):
  44. for i in index_list:
  45. new_index = self.data_base[i.collection].create_indexes(indexes=i.index)[0]
  46. self.update_index_status(i.collection, new_index)
  47.  
  48. def drop_old_index(self):
  49. for coll in self.all_index:
  50. for index in self.all_index[coll]:
  51. if self.all_index[coll][index]:
  52. self.data_base[coll].drop_index(index)
  53. self.logging.info('Drop index (coll, index): {}, {}, ok'.format(coll, index))
  54.  
  55. def auto_create(self):
  56. self.create_index(self.index_list)
  57. self.drop_old_index()
  58.  
  59.  
  60. def main():
  61. index_list = [
  62. InL(coll='users',
  63. ind=[('key', ASCENDING)],
  64. unique=True),
  65. InL(coll='users',
  66. ind=[('key_name', TEXT), ('key_title', TEXT)]),
  67. InL(coll='users', ind=[('tags', ASCENDING)]),
  68.  
  69. InL(coll='users',
  70. ind=[('t_id', ASCENDING)],
  71. unique=True),
  72. ]
  73.  
  74. ci = CreateIndex(host=os.environ['MONGO_HOST'], username=os.environ.get('MONGO_USER'), password=os.environ.get('MONGO_PASSWD'), db_name='bot_db', index_list=index_list)
  75. ci.auto_create()
  76.  
  77.  
  78. if __name__ == '__main__':
  79. main()
Add Comment
Please, Sign In to add comment