How to make an index In azure cosmos DB just Like Azure AI Search?

Ahmad Shafiq 150 Reputation points
2025-03-11T08:34:18.35+00:00

I want to create an Index inside my azure cosmos DB just like an azure AI Search Index, So that I can use that Index with Azure Open AI Rest API?

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,786 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Adithya Prasad K 90 Reputation points Microsoft External Staff
    2025-03-12T09:16:36.7166667+00:00

    Hi Ahmad Shafiq
    Greetings!
    To create a vector index in Azure Cosmos DB for MongoDB vCore and harness the capabilities of Azure OpenAI for Retrieval-Augmented Generation (RAG), follow these steps:

    Setting Up the Database and Collection

    1. Establish a Connection: Use the pymongo library to connect to your Azure Cosmos DB for MongoDB vCore instance. Replace <USERNAME>, <PASSWORD>, and <VCORE_CLUSTER_NAME> with your actual credentials and cluster name.
        import pymongo
        mongo_conn = "mongodb+srv://<USERNAME>:<PASSWORD>@<VCORE_CLUSTER_NAME>.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000"
        mongo_client = pymongo.MongoClient(mongo_conn)
    
    1. Create a Database and Collection: Define the database and collection names, then create them within your Cosmos DB instance.
        DATABASE_NAME = "AdgenDatabase"    COLLECTION_NAME = "AdgenCollection"    mongo_client.drop_database(DATABASE_NAME)    db = mongo_client[DATABASE_NAME]    collection = db[COLLECTION_NAME]    if COLLECTION_NAME not in db.list_collection_names():        db.create_collection(COLLECTION_NAME)        print(f"Created collection '{COLLECTION_NAME}'.")    else:        print(f"Using collection: '{COLLECTION_NAME}'.")
    

    Creating a Vector Index

    1. Create the Vector Index: To perform efficient vector similarity searches within your collection, create a vector index. Azure Cosmos DB supports different types of vector indexes, such as IVF and HNSW.
        # Example for creating a vector index (specific commands may vary)
        collection.create_index([("vector_field", pymongo.ASCENDING)], name="vector_index")
    

    Additional Resources

    For more detailed information and examples, you can refer to the following resources:

    By following these steps, you can effectively create a vector index in Azure Cosmos DB for MongoDB vCore and leverage the capabilities of Azure OpenAI for RAG without using AI Search. If you have any further questions or need additional assistance, feel free to ask!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.