Home > Blockchain >  Python MongoDB Motor dynamically create Indexes
Python MongoDB Motor dynamically create Indexes

Time:09-08

I am attempting to write a function which will async create Indexes for each of my collections dynamically. The struggle I am having is accessing the class instance of each of my collections, and then calling the object to create the index.

I have tried:

  • getattr
  • ast.literal_eval

NOTE: I am unable to use eval() for security reasons

Example of how my class instance looks:

import ast
from models.database_models import IndexedKeyModels


class Mongo:  # pylint: disable=too-many-instance-attributes
    def __init__(self):
        self.connection = self.get_set_connection() # Function to create MongoDB connection
        self.db = self.connection.pal_db
        self.test1 = self.db.test1
        self.test2 = self.db.test2

    async def set_indexes(self) -> None:

        test_string: str = ""
        if self.dev == "True":
            test_string  = "test_"
        for name in IndexedKeyModels():
            await ast.literal_eval(
                f"self.{test_string}{name[0]}.create_index([('{name[1]}', {ASCENDING})], background=True)"
            )

The IndexedKeyModels looks like this:

class IndexedKeyModels(BaseModel):
    """
    MongoDB Indexed Key names
    """

    test1: str = "Index1"
    test2: str = "Index2"

I would like to be able to dynamically create each Index for each collection without having to define each create_index for each collection we have.

CodePudding user response:

If you want to create an index on a specific collection and field, you can do this programatically with this construct:

collectionname = 'coll1'
fieldname = 'field1'
db[collectionname].create_index([(fieldname , pymongo.ASCENDING)])
  • Related