Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import logging
- from pymongo import ASCENDING, TEXT
- from pymongo import MongoClient, IndexModel, ASCENDING, DESCENDING
- class InL:
- def __init__(self, coll, ind, unique=False, name=None):
- self.collection = coll
- if name is None:
- index = IndexModel(ind, unique=unique)
- else:
- index = IndexModel(ind, unique=unique, name=name)
- self.index = [index]
- class CreateIndex:
- def set_all_index(self):
- self.all_index = {}
- for coll in self.data_base.collection_names():
- self.all_index[coll] = {i: True for i in self.data_base[coll].index_information() if i[0] != '_'}
- def __init__(self, host, username, password, db_name, index_list):
- self.index_list = index_list
- mongodb_client = MongoClient(host=host, username=username, password=password)
- self.data_base = mongodb_client[db_name]
- self.all_index = None
- self.set_all_index()
- self.logging = logging.getLogger('mg_create_index')
- def update_index_status(self, collection, index_name):
- if self.all_index.get(collection, {}).get(index_name):
- self.all_index[collection][index_name] = False
- self.logging.info('Update index (coll, index): {}, {}, ok'.format(collection, index_name))
- else:
- self.logging.info('Create new index (coll, index): {}, {}, ok'.format(collection, index_name))
- def create_index(self, index_list):
- for i in index_list:
- new_index = self.data_base[i.collection].create_indexes(indexes=i.index)[0]
- self.update_index_status(i.collection, new_index)
- def drop_old_index(self):
- for coll in self.all_index:
- for index in self.all_index[coll]:
- if self.all_index[coll][index]:
- self.data_base[coll].drop_index(index)
- self.logging.info('Drop index (coll, index): {}, {}, ok'.format(coll, index))
- def auto_create(self):
- self.create_index(self.index_list)
- self.drop_old_index()
- def main():
- index_list = [
- InL(coll='users',
- ind=[('key', ASCENDING)],
- unique=True),
- InL(coll='users',
- ind=[('key_name', TEXT), ('key_title', TEXT)]),
- InL(coll='users', ind=[('tags', ASCENDING)]),
- InL(coll='users',
- ind=[('t_id', ASCENDING)],
- unique=True),
- ]
- 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)
- ci.auto_create()
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment