public void CreateVectorIndexIfNotExists()

in src/WebJobs.Extensions.OpenAI.CosmosDBSearch/CosmosDBSearchProvider.cs [170:210]


    public void CreateVectorIndexIfNotExists(MongoClient cosmosClient)
    {
        try
        {
            using IAsyncCursor<BsonDocument> indexCursor = cosmosClient
                .GetDatabase(this.databaseName)
                .GetCollection<BsonDocument>(this.collectionName)
                .Indexes.List();
            bool vectorIndexExists = indexCursor.ToList().Any(x => x["name"] == this.indexName);
            if (!vectorIndexExists)
            {
                BsonDocument vectorIndexDefinition = new BsonDocument();
                switch (this.cosmosDBSearchConfigOptions.Value.Kind)
                {
                    case "vector-ivf":
                        vectorIndexDefinition = this.GetIndexDefinitionVectorIVF();
                        break;
                    case "vector-hnsw":
                        vectorIndexDefinition = this.GetIndexDefinitionVectorHNSW();
                        break;
                    case "vector-diskann":
                        vectorIndexDefinition = this.GetIndexDefinitionVectorDiskANN();
                        break;
                }

                BsonDocumentCommand<BsonDocument> command = new(vectorIndexDefinition);
                BsonDocument result = cosmosClient.GetDatabase(this.databaseName).RunCommand(command);
                if (result["ok"] != 1)
                {
                    this.logger.LogError("CreateIndex failed with response: " + result.ToJson());
                }
            }

        }
        catch (MongoException ex)
        {
            this.logger.LogError(ex, "CosmosDBSearchProvider:CreateVectorIndexIfNotExists error");
            throw;
        }

    }