快速入門:在 Azure DocumentDB 中使用 .NET 的向量搜尋

在 Azure DocumentDB 中使用向量搜尋,搭配 .NET MongoDB 驅動程式,以有效儲存與查詢向量資料。

這份快速入門透過 GitHub 上的 .NET 範例應用程式,提供關鍵向量搜尋技術的導覽。

應用程式使用 JSON 檔案中的範例飯店資料集,其中包含來自 text-embedding-3-small 模型預先計算的向量。 你也可以自己生成向量。 飯店資料包括飯店名稱、位置、說明和向量內嵌。

Prerequisites

  • Azure 訂用帳戶。 如果您沒有 Azure 訂閱,請建立免費帳戶。

Tip

若要在部署前自訂 Azure OpenAI 模型參數,請參閱本文後續的「自訂 Azure OpenAI 部署」章節。

應用程式相依性

應用程式會使用下列 NuGet 套件:

設定並執行應用程式

請完成以下步驟,用您自己的數值配置應用程式,並對您的 Azure DocumentDB 叢集進行搜尋。

設定應用程式

請以您自己的值更新 appsettings.json 預留位置。

{
  "AzureOpenAI": {
    "TenantId": "<your-tenant-id>",
    "EmbeddingModel": "text-embedding-3-small",
    "ApiVersion": "2023-05-15",
    "Endpoint": "https://<your-openai-service-name>.openai.azure.com/"
  },
  "DataFiles": {
    "WithoutVectors": "data/Hotels.json",
    "WithVectors": "data/Hotels_Vector.json"
  },
  "Embedding": {
    "FieldToEmbed": "Description",
    "EmbeddedField": "DescriptionVector",
    "Dimensions": 1536,
    "BatchSize": 16
  },
  "MongoDB": {
    "TenantId": "<your-tenant-id>",
    "ClusterName": "<your-cluster-name>",
    "LoadBatchSize": 100
  },
  "VectorSearch": {
    "Query": "quintessential lodging near running trails, eateries, retail",
    "DatabaseName": "Hotels",
    "TopK": 5
  }
}

向 Azure 驗證

範例應用程式會透過 DefaultAzureCredential 和 Microsoft Entra ID 使用無密碼驗證。 在執行應用程式之前,請使用支援的工具(例如 Azure CLI 或 Azure PowerShell)登入 Azure。 這些工具有助於確保應用程式能安全地存取 Azure 資源。

Note

請確保您已登入的身分在 Azure DocumentDB 帳戶與 Azure OpenAI 資源上都具備所需的資料平面角色。

az login

建置並執行專案

範例應用程式會在 MongoDB 集合中填充向量化的範例資料。 您可以執行不同類型的搜尋查詢。

  1. 使用命令 dotnet run 啟動應用程式:

    dotnet run
    

    該應用程序會打印一個菜單供您選擇數據庫和搜索選項:

    === DocumentDB Vector Samples Menu ===
    Please enter your choice (0-5):
    1. Create embeddings for data
    2. Show all database indexes
    3. Run IVF vector search
    4. Run HNSW vector search
    5. Run DiskANN vector search
    0. Exit
    
  2. 輸入 5 並選擇 Enter。

    應用程式填入資料庫並執行搜尋後,您會看到符合所選向量搜尋查詢的前五家飯店。 你也會看到他們的相似度分數。

    應用程式記錄和輸出顯示:

    • 集合建立與資料插入狀態。
    • 向量索引建立確認。
    • 搜尋結果包含飯店名稱、地點及相似度分數。

    輸出範例 (為簡潔起見而縮短):

    MongoDB client initialized with passwordless authentication
    Starting DiskANN vector search workflow
    Collection is empty, loading data from file
    Successfully loaded 50 documents into collection
    Creating vector index 'vectorIndex_diskann'
    Vector index 'vectorIndex_diskann' is ready for DiskANN search
    Executing DiskANN vector search for top 5 results
    
    Search Results (5 found using DiskANN):
    1. Royal Cottage Resort (Similarity: 0.4991)
    2. Country Comfort Inn (Similarity: 0.4786)
    3. Nordick's Valley Motel (Similarity: 0.4635)
    4. Economy Universe Motel (Similarity: 0.4461)
    5. Roach Motel (Similarity: 0.4388)
    

探索應用程式程式碼

下列各節提供範例應用程式中最重要服務和程式碼的詳細資料。 請造訪 GitHub 倉庫以探索完整的應用程式程式碼。

探索搜尋服務

VectorSearchService 協調端對端向量相似性搜尋。 該服務採用反向檔案(IVF)、階層式可導覽小世界(HNSW)及 DiskANN 搜尋技術,搭配 Azure OpenAI 嵌入。

using Azure.AI.OpenAI;
using Azure.Identity;
using DocumentDBVectorSamples.Models;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;

namespace DocumentDBVectorSamples.Services.VectorSearch;

/// <summary>
/// Service for performing vector similarity searches using different algorithms (IVF, HNSW, DiskANN).
/// Handles data loading, vector index creation, query embedding generation, and search execution.
/// </summary>
public class VectorSearchService
{
    private readonly ILogger<VectorSearchService> _logger;
    private readonly AzureOpenAIClient _openAIClient;
    private readonly MongoDbService _mongoService;
    private readonly AppConfiguration _config;

    public VectorSearchService(ILogger<VectorSearchService> logger, MongoDbService mongoService, AppConfiguration config)
    {
        _logger = logger;
        _mongoService = mongoService;
        _config = config;
        
        // Initialize Azure OpenAI client with passwordless authentication
        var credentialOptions = new DefaultAzureCredentialOptions();
        if (!string.IsNullOrEmpty(_config.AzureOpenAI.TenantId))
        {
            credentialOptions.TenantId = _config.AzureOpenAI.TenantId;
        }
        var credential = new DefaultAzureCredential(credentialOptions);
        _openAIClient = new AzureOpenAIClient(new Uri(_config.AzureOpenAI.Endpoint), credential);
    }

    /// <summary>
    /// Executes a complete vector search workflow: data setup, index creation, query embedding, and search
    /// </summary>
    /// <param name="indexType">The vector search algorithm to use (IVF, HNSW, or DiskANN)</param>
    public async Task RunSearchAsync(VectorIndexType indexType)
    {
        try
        {
            _logger.LogInformation($"Starting {indexType} vector search workflow");
            
            // Setup collection
            var collectionSuffix = indexType switch 
            { 
                VectorIndexType.IVF => "ivf", 
                VectorIndexType.HNSW => "hnsw", 
                VectorIndexType.DiskANN => "diskann", 
                _ => throw new ArgumentException($"Unknown index type: {indexType}") 
            };
            var collectionName = $"hotels_{collectionSuffix}";
            var indexName = $"vectorIndex_{collectionSuffix}";
            
            var collection = _mongoService.GetCollection<HotelData>(_config.VectorSearch.DatabaseName, collectionName);
            
            // Load data from file if collection is empty
            var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
            var dataFilePath = Path.Combine(assemblyLocation, _config.DataFiles.WithVectors);
            await _mongoService.LoadDataIfNeededAsync(collection, dataFilePath);

            // Create the vector index with algorithm-specific search options
            var searchOptions = indexType switch
            {
                VectorIndexType.IVF => CreateIVFSearchOptions(_config.Embedding.Dimensions),
                VectorIndexType.HNSW => CreateHNSWSearchOptions(_config.Embedding.Dimensions),
                VectorIndexType.DiskANN => CreateDiskANNSearchOptions(_config.Embedding.Dimensions),
                _ => throw new ArgumentException($"Unknown index type: {indexType}")
            };
            
            await _mongoService.CreateVectorIndexAsync(
                _config.VectorSearch.DatabaseName, collectionName, indexName,
                _config.Embedding.EmbeddedField, searchOptions);
            
            _logger.LogInformation($"Vector index '{indexName}' is ready for {indexType} search");
            await Task.Delay(5000); // Allow index to be fully initialized

            // Create embedding for the query
            var embeddingClient = _openAIClient.GetEmbeddingClient(_config.AzureOpenAI.EmbeddingModel);
            var queryEmbedding = (await embeddingClient.GenerateEmbeddingAsync(_config.VectorSearch.Query)).Value.ToFloats().ToArray();
            _logger.LogInformation($"Generated query embedding with {queryEmbedding.Length} dimensions");

            // Build MongoDB aggregation pipeline for vector search
            var searchPipeline = new BsonDocument[]
            {
                // Vector similarity search using cosmosSearch
                new BsonDocument("$search", new BsonDocument
                {
                    ["cosmosSearch"] = new BsonDocument
                    {
                        ["vector"] = new BsonArray(queryEmbedding.Select(f => new BsonDouble(f))),
                        ["path"] = _config.Embedding.EmbeddedField,  // Field containing embeddings
                        ["k"] = _config.VectorSearch.TopK           // Number of results to return
                    }
                }),
                // Project results with similarity scores
                new BsonDocument("$project", new BsonDocument
                {
                    ["score"] = new BsonDocument("$meta", "searchScore"),
                    ["document"] = "$$ROOT"
                })
            };

            // Execute and process the search
            _logger.LogInformation($"Executing {indexType} vector search for top {_config.VectorSearch.TopK} results");
            var searchResults = (await collection.AggregateAsync<BsonDocument>(searchPipeline)).ToList()
                .Select(result => new SearchResult 
                { 
                    Document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<HotelData>(result["document"].AsBsonDocument), 
                    Score = result["score"].AsDouble 
                }).ToList();

            // Print the results
            if (searchResults?.Count == 0) 
            { 
                _logger.LogInformation("❌ No search results found. Check query terms and data availability."); 
            }
            else
            {
                _logger.LogInformation($"\n✅ Search Results ({searchResults!.Count} found using {indexType}):");
                for (int i = 0; i < searchResults.Count; i++)
                {
                    var result = searchResults[i];
                    var hotelName = result.Document?.HotelName ?? "Unknown Hotel";
                    _logger.LogInformation($"  {i + 1}. {hotelName} (Similarity: {result.Score:F4})");
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"{indexType} vector search failed");
            throw;
        }
    }

    /// <summary>
    /// Creates IVF (Inverted File) search options - good for large datasets with fast approximate search
    /// </summary>
    private BsonDocument CreateIVFSearchOptions(int dimensions) => new BsonDocument
    {
        ["kind"] = "vector-ivf",
        ["similarity"] = "COS",
        ["dimensions"] = dimensions,
        ["numLists"] = 1
    };

    /// <summary>
    /// Creates HNSW (Hierarchical Navigable Small World) search options - best accuracy/speed balance
    /// </summary>
    private BsonDocument CreateHNSWSearchOptions(int dimensions) => new BsonDocument
    {
        ["kind"] = "vector-hnsw",
        ["similarity"] = "COS",
        ["dimensions"] = dimensions,
        ["m"] = 16,
        ["efConstruction"] = 64
    };

    /// <summary>
    /// Creates DiskANN search options - optimized for very large datasets stored on disk
    /// </summary>
    private BsonDocument CreateDiskANNSearchOptions(int dimensions) => new BsonDocument
    {
        ["kind"] = "vector-diskann",
        ["similarity"] = "COS",
        ["dimensions"] = dimensions
    };
}

在上述程式碼中,VectorSearchService 執行下列工作:

  • 根據所請求的演算法決定集合名稱與索引名稱。

  • 建立或取得 MongoDB 集合,若集合為空則載入 JSON 資料。

  • 建立演算法專屬的索引選項(例如 IVF、HNSW 或 DiskANN),並確保向量索引的存在。

  • 透過 Azure OpenAI 為已設定的查詢產生嵌入。

  • 建構並執行彙總搜尋管線。

  • 反序列化並列印結果。

探索 Azure DocumentDB 服務

它MongoDbService管理與 Azure DocumentDB 的互動。 該服務處理載入資料、建立向量索引、索引列表及大量插入等任務,用於飯店向量搜尋。

using Azure.Identity;
using DocumentDBVectorSamples.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;

namespace DocumentDBVectorSamples.Services;

/// <summary>
/// Service for MongoDB operations including data insertion, index management, and vector index creation.
/// Supports Azure DocumentDB with passwordless authentication.
/// </summary>
public class MongoDbService
{
    private readonly ILogger<MongoDbService> _logger;
    private readonly AppConfiguration _config;
    private readonly MongoClient _client;

    public MongoDbService(ILogger<MongoDbService> logger, IConfiguration configuration)
    {
        _logger = logger;
        _config = new AppConfiguration();
        configuration.Bind(_config);
        
        // Validate configuration
        if (string.IsNullOrEmpty(_config.MongoDB.ClusterName))
            throw new InvalidOperationException("MongoDB connection not configured. Please provide ConnectionString or ClusterName.");
            
        // Configure MongoDB connection for Azure DocumentDB with OIDC authentication
        var connectionString = $"mongodb+srv://{_config.MongoDB.ClusterName}.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=MONGODB-OIDC&retrywrites=false&maxIdleTimeMS=120000";
        var settings = MongoClientSettings.FromUrl(MongoUrl.Create(connectionString));
        settings.UseTls = true;
        settings.RetryWrites = false;
        settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2);
        settings.Credential = MongoCredential.CreateOidcCredential(new AzureIdentityTokenHandler(new DefaultAzureCredential(), _config.MongoDB.TenantId));
        settings.Freeze();
        
        _client = new MongoClient(settings);
        _logger.LogInformation("MongoDB client initialized with passwordless authentication");
    }

    /// <summary>Gets a database instance by name</summary>
    public IMongoDatabase GetDatabase(string databaseName) => _client.GetDatabase(databaseName);
    
    /// <summary>Gets a collection instance from the specified database</summary>
    public IMongoCollection<T> GetCollection<T>(string databaseName, string collectionName) => 
        _client.GetDatabase(databaseName).GetCollection<T>(collectionName);

    /// <summary>Drops a collection from the specified database</summary>
    public async Task DropCollectionAsync(string databaseName, string collectionName)
    {
        _logger.LogInformation($"Dropping collection '{collectionName}' from database '{databaseName}'");
        await _client.GetDatabase(databaseName).DropCollectionAsync(collectionName);
        _logger.LogInformation($"Collection '{collectionName}' dropped successfully");
    }

    /// <summary>
    /// Creates a vector search index for DocumentDB, with support for IVF, HNSW, and DiskANN algorithms
    /// </summary>
    public async Task<BsonDocument> CreateVectorIndexAsync(string databaseName, string collectionName, string indexName, string embeddedField, BsonDocument cosmosSearchOptions)
    {
        var database = _client.GetDatabase(databaseName);
        var collection = database.GetCollection<BsonDocument>(collectionName);
        
        // Check if index already exists to avoid duplication
        var indexList = await (await collection.Indexes.ListAsync()).ToListAsync();
        if (indexList.Any(index => index.TryGetValue("name", out var nameValue) && nameValue.AsString == indexName))
        {
            _logger.LogInformation($"Vector index '{indexName}' already exists, skipping creation");
            return new BsonDocument { ["ok"] = 1 };
        }
        
        // Create the specified vector index type
        _logger.LogInformation($"Creating vector index '{indexName}' on field '{embeddedField}'");
        return await database.RunCommandAsync<BsonDocument>(new BsonDocument
        {
            ["createIndexes"] = collectionName,
            ["indexes"] = new BsonArray 
            { 
                new BsonDocument 
                { 
                    ["name"] = indexName, 
                    ["key"] = new BsonDocument { [embeddedField] = "cosmosSearch" }, 
                    ["cosmosSearchOptions"] = cosmosSearchOptions 
                } 
            }
        });
    }

    /// <summary>
    /// Displays all indexes across all user databases, excluding system databases
    /// </summary>
    public async Task ShowAllIndexesAsync()
    {
        try
        {
            // Get user databases (exclude system databases)
            var databases = (await (await _client.ListDatabaseNamesAsync()).ToListAsync())
                .Where(name => !new[] { "admin", "config", "local" }.Contains(name)).ToList();
                
            if (!databases.Any()) 
            { 
                _logger.LogInformation("No user databases found or access denied"); 
                return; 
            }

            foreach (var dbName in databases)
            {
                var database = _client.GetDatabase(dbName);
                var collections = await (await database.ListCollectionNamesAsync()).ToListAsync();
                
                if (!collections.Any()) 
                { 
                    _logger.LogInformation($"Database '{dbName}': No collections found"); 
                    continue; 
                }
                
                _logger.LogInformation($"\n📂 DATABASE: {dbName} ({collections.Count} collections)");
                
                // Display indexes for each collection
                foreach (var collName in collections)
                {
                    try
                    {
                        var indexList = await (await database.GetCollection<BsonDocument>(collName).Indexes.ListAsync()).ToListAsync();
                        _logger.LogInformation($"\n  🗃️ COLLECTION: {collName} ({indexList.Count} indexes)");
                        indexList.ForEach(index => _logger.LogInformation($"    Index: {index.ToJson()}"));
                    }
                    catch (Exception ex) 
                    { 
                        _logger.LogError(ex, $"Failed to list indexes for collection '{collName}'"); 
                    }
                }
            }
        }
        catch (Exception ex) 
        { 
            _logger.LogError(ex, "Failed to retrieve database indexes"); 
            throw; 
        }
    }

    /// <summary>
    /// Loads data from file into collection if the collection is empty
    /// </summary>
    /// <param name="collection">Target collection to load data into</param>
    /// <param name="dataFilePath">Path to the JSON data file containing vector embeddings</param>
    /// <returns>Number of documents loaded, or 0 if collection already had data</returns>
    public async Task<int> LoadDataIfNeededAsync<T>(IMongoCollection<T> collection, string dataFilePath) where T : class
    {
        var existingDocCount = await collection.CountDocumentsAsync(Builders<T>.Filter.Empty);

        // Skip loading if collection already has data
        if (existingDocCount > 0)
        {
            _logger.LogInformation("Collection already contains data, skipping load operation");
            return 0;
        }

        // Load and validate data file
        _logger.LogInformation("Collection is empty, loading data from file");
        if (!File.Exists(dataFilePath))
            throw new FileNotFoundException($"Vector data file not found: {dataFilePath}");

        var jsonContent = await File.ReadAllTextAsync(dataFilePath);
        var data = JsonConvert.DeserializeObject<List<T>>(jsonContent) ?? new List<T>();
        
        if (data.Count == 0)
            throw new InvalidOperationException("No data found in the vector data file");

        // Insert data using existing method
        var summary = await InsertDataAsync(collection, data);
        _logger.LogInformation($"Successfully loaded {summary.Inserted} documents into collection");
        
        return summary.Inserted;
    }

    /// <summary>
    /// Inserts data into MongoDB collection, converts JSON embeddings to float arrays, and creates standard indexes
    /// </summary>
    public async Task<InsertSummary> InsertDataAsync<T>(IMongoCollection<T> collection, IEnumerable<T> data)
    {
        var dataList = data.ToList();
        _logger.LogInformation($"Processing {dataList.Count} items for insertion");

        // Convert JSON array embeddings to float arrays for vector search compatibility
        foreach (var hotel in dataList.OfType<HotelData>().Where(h => h.ExtraElements != null))
            foreach (var kvp in hotel.ExtraElements.ToList().Where(k => k.Value is Newtonsoft.Json.Linq.JArray))
                hotel.ExtraElements[kvp.Key] = ((Newtonsoft.Json.Linq.JArray)kvp.Value).Select(token => (float)token).ToArray();

        int inserted = 0, failed = 0;
        try
        {
            // Use unordered insert for better performance
            await collection.InsertManyAsync(dataList, new InsertManyOptions { IsOrdered = false });
            inserted = dataList.Count;
            _logger.LogInformation($"Successfully inserted {inserted} items");
        }
        catch (Exception ex)
        {
            failed = dataList.Count;
            _logger.LogError(ex, $"Batch insert failed for {dataList.Count} items");
        }

        // Create standard indexes for common query fields
        var indexFields = new[] { "HotelId", "Category", "Description", "Description_fr" };
        foreach (var field in indexFields)
            await collection.Indexes.CreateOneAsync(new CreateIndexModel<T>(Builders<T>.IndexKeys.Ascending(field)));

        return new InsertSummary { Total = dataList.Count, Inserted = inserted, Failed = failed };
    }

    /// <summary>Disposes the MongoDB client and its resources</summary>
    public void Dispose() => _client?.Cluster?.Dispose();
}

在上述程式碼中,MongoDbService 執行下列工作:

  • 讀取設定並建立一個使用 Azure 憑證的無密碼用戶端。

  • 隨時提供資料庫或集合參照。

  • 只有當向量搜尋索引尚未存在時,才建立該索引。

  • 列出所有非系統資料庫、其集合以及每個集合的索引。

  • 如果集合為空,則插入範例資料,並新增支援索引。

在 Visual Studio Code 中檢視和管理資料

  1. 在 Visual Studio Code 中安裝 Azure DocumentDB 擴充功能與 C# 擴充功能。

  2. 使用 Azure DocumentDB 擴充功能連接您的 Azure DocumentDB 帳戶。

  3. 查看 Hotels 資料庫中的資料與索引。

    DocumentDB 擴充功能顯示 Azure DocumentDB 集合的螢幕截圖。

自訂 Azure OpenAI 部署(選用)

基礎架構部署 Azure OpenAI 時,預設模型與區域設定在 infra/main.bicepparam中定義。 在執行 azd up之前,您可以自訂以下任一參數:

Parameter Default Description
AZURE_OPENAI_LOCATION 與 AZURE_LOCATION 相同 OpenAI 資源部署的區域
AZURE_OPENAI_EMBEDDING_MODEL text-embedding-3-small 嵌入模型名稱
AZURE_OPENAI_EMBEDDING_MODEL_VERSION 1 嵌入模型版本
AZURE_OPENAI_EMBEDDING_MODEL_TYPE Standard 部署類型(Standard 或 GlobalStandard)

若要覆寫預設值,請在執行azd env set前使用azd up:

# Deploy OpenAI to a different region than your other resources
azd env set AZURE_OPENAI_LOCATION swedencentral

# Switch deployment type from Standard (default) to GlobalStandard
azd env set AZURE_OPENAI_EMBEDDING_MODEL_TYPE GlobalStandard

# Change the embedding model
azd env set AZURE_OPENAI_EMBEDDING_MODEL text-embedding-3-small
azd env set AZURE_OPENAI_EMBEDDING_MODEL_VERSION 1

Note

並非所有模型在所有地區或所有部署類型都能取得。 請依區域查詢 Azure OpenAI 模型的可用性,了解支援的組合。

排除 Azure OpenAI 佈建失敗問題

如果你azd up在建立 Azure OpenAI 資源或部署模型時失敗,很可能是因為以下其中一種問題:

  • 區域可用性:該模型在您選擇的區域中無法取得。 嘗試使用 azd env set AZURE_OPENAI_LOCATION <different-region>(例如,eastus2 或 swedencentral)。

  • 部署類型不符:模型不支援您區域所選的部署類型。 使用azd env set AZURE_OPENAI_EMBEDDING_MODEL_TYPE GlobalStandard在GlobalStandard與Standard之間切換。

  • 配額限制:您的訂閱已達到所選模型、區域或部署類型組合的配額。 請在 Azure 入口網站的 Azure OpenAI>配額下檢查您的配額。 您可以申請增加配額,或嘗試您有空容量的其他區域。

  • 模型已停用或不可用:Azure OpenAI 會定期淘汰較舊的模型版本。 如果部署失敗,因為模型版本已不再可用,請使用 azd env set AZURE_OPENAI_EMBEDDING_MODEL_VERSION <new-version>。 請查詢 Azure OpenAI 模型退役,以取得目前的模型生命週期狀態。

變更任何參數後,請再次執行 azd up 以重試部署。

清理資源

當您不再需要它們時,請刪除資源群組、Azure DocumentDB 叢集及 Azure OpenAI 資源,以避免不必要的成本。