使用 Azure CosmosDB NoSQL 矢量存储连接器(预览版)

警告

语义内核向量存储功能处于预览状态,需要中断性变更的改进可能仍发生在发布前的有限情况下。

概述

Azure CosmosDB NoSQL 矢量存储连接器可用于访问和管理 Azure CosmosDB NoSQL 中的数据。 连接器具有以下特征。

功能区域 支持
集合映射到 Azure Cosmos DB NoSQL 容器
支持的键属性类型
  • string
  • AzureCosmosDBNoSQLCompositeKey
支持的数据属性类型
  • string
  • int
  • long
  • double
  • float
  • 布尔
  • DateTimeOffset
  • 和枚举每种类型
支持的向量属性类型
  • ReadOnlyMemory<float>
  • ReadOnlyMemory<字节>
  • ReadOnlyMemory<sbyte>
  • ReadOnlyMemory<Half>
支持的索引类型
  • 平面
  • QuantizedFlat
  • DiskAnn
支持的距离函数
  • CosineSimilarity
  • DotProductSimilarity
  • EuclideanDistance
支持的筛选器子句
  • AnyTagEqualTo
  • EqualTo
支持记录中的多个向量
是否支持Filterable?
是否支持FullTextSearchable?
支持 StoragePropertyName? 否,请改用 JsonSerializerOptionsJsonPropertyNameAttribute 改用。 有关详细信息,请参阅此处。

局限性

手动初始化 CosmosClient 时,必须指定 CosmosClientOptions.UseSystemTextJsonSerializerWithOptions,因为默认序列化程序存在限制。 此选项可以设置为 JsonSerializerOptions.Default 或使用其他序列化程序选项进行自定义以满足特定配置需求。

var cosmosClient = new CosmosClient(connectionString, new CosmosClientOptions()
{
    UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Default,
});

入门

将 Azure CosmosDB NoSQL Vector Store 连接器 NuGet 包添加到项目。

dotnet add package Microsoft.SemanticKernel.Connectors.AzureCosmosDBNoSQL --prerelease

可以使用语义内核提供的扩展方法将向量存储添加到可用的 KernelBuilder 依赖项注入容器或 IServiceCollection 依赖项注入容器。

using Microsoft.SemanticKernel;

// Using Kernel Builder.
var kernelBuilder = Kernel
    .CreateBuilder()
    .AddAzureCosmosDBNoSQLVectorStore(connectionString, databaseName);
using Microsoft.SemanticKernel;

// Using IServiceCollection with ASP.NET Core.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAzureCosmosDBNoSQLVectorStore(connectionString, databaseName);

还提供不带参数的扩展方法。 这些要求将实例 Microsoft.Azure.Cosmos.Database 单独注册到依赖项注入容器。

using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;

// Using Kernel Builder.
var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.Services.AddSingleton<Database>(
    sp =>
    {
        var cosmosClient = new CosmosClient(connectionString, new CosmosClientOptions()
        {
            // When initializing CosmosClient manually, setting this property is required 
            // due to limitations in default serializer. 
            UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Default,
        });

        return cosmosClient.GetDatabase(databaseName);
    });
kernelBuilder.AddAzureCosmosDBNoSQLVectorStore();
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;

// Using IServiceCollection with ASP.NET Core.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<Database>(
    sp =>
    {
        var cosmosClient = new CosmosClient(connectionString, new CosmosClientOptions()
        {
            // When initializing CosmosClient manually, setting this property is required 
            // due to limitations in default serializer. 
            UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Default,
        });

        return cosmosClient.GetDatabase(databaseName);
    });
builder.Services.AddAzureCosmosDBNoSQLVectorStore();

可以直接构造 Azure CosmosDB NoSQL 矢量存储实例。

using Microsoft.Azure.Cosmos;
using Microsoft.SemanticKernel.Connectors.AzureCosmosDBNoSQL;

var cosmosClient = new CosmosClient(connectionString, new CosmosClientOptions()
{
    // When initializing CosmosClient manually, setting this property is required 
    // due to limitations in default serializer. 
    UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Default,
});

var database = cosmosClient.GetDatabase(databaseName);
var vectorStore = new AzureCosmosDBNoSQLVectorStore(database);

可以构造对命名集合的直接引用。

using Microsoft.Azure.Cosmos;
using Microsoft.SemanticKernel.Connectors.AzureCosmosDBNoSQL;

var cosmosClient = new CosmosClient(connectionString, new CosmosClientOptions()
{
    // When initializing CosmosClient manually, setting this property is required 
    // due to limitations in default serializer. 
    UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Default,
});

var database = cosmosClient.GetDatabase(databaseName);
var collection = new AzureCosmosDBNoSQLVectorStoreRecordCollection<Hotel>(
    database,
    "skhotels");

数据映射

从数据模型到存储时,Azure CosmosDB NoSQL Vector Store 连接器提供默认映射器。

此映射器将数据模型上的属性列表直接转换为 Azure CosmosDB NoSQL 中的字段,并用于 System.Text.Json.JsonSerializer 转换为存储架构。 这意味着,如果需要与数据模型属性名称不同的存储名称,则支持使用该 JsonPropertyNameAttribute 名称。 唯一的例外是映射到名为 id的数据库字段的记录的键,因为所有 CosmosDB NoSQL 记录都必须将此名称用于 ID。

还可以使用具有自定义属性命名策略的自定义 JsonSerializerOptions 实例。 若要启用此功能,必须将该 JsonSerializerOptions 属性传递到 AzureCosmosDBNoSQLVectorStoreRecordCollection 构造中。

using System.Text.Json;
using Microsoft.Azure.Cosmos;
using Microsoft.SemanticKernel.Connectors.AzureCosmosDBNoSQL;

var jsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseUpper };

var cosmosClient = new CosmosClient(connectionString, new CosmosClientOptions()
{
    // When initializing CosmosClient manually, setting this property is required 
    // due to limitations in default serializer. 
    UseSystemTextJsonSerializerWithOptions = jsonSerializerOptions
});

var database = cosmosClient.GetDatabase(databaseName);
var collection = new AzureCosmosDBNoSQLVectorStoreRecordCollection<Hotel>(
    database,
    "skhotels",
    new() { JsonSerializerOptions = jsonSerializerOptions });

使用上述自定义 JsonSerializerOptionsSnakeCaseUpper以下数据模型将映射到以下 json。

using System.Text.Json.Serialization;
using Microsoft.Extensions.VectorData;

public class Hotel
{
    [VectorStoreRecordKey]
    public ulong HotelId { get; set; }

    [VectorStoreRecordData(IsFilterable = true)]
    public string HotelName { get; set; }

    [VectorStoreRecordData(IsFullTextSearchable = true)]
    public string Description { get; set; }

    [JsonPropertyName("HOTEL_DESCRIPTION_EMBEDDING")]
    [VectorStoreRecordVector(4, DistanceFunction.EuclideanDistance, IndexKind.QuantizedFlat)]
    public ReadOnlyMemory<float>? DescriptionEmbedding { get; set; }
}
{
    "id": 1,
    "HOTEL_NAME": "Hotel Happy",
    "DESCRIPTION": "A place where everyone can be happy.",
    "HOTEL_DESCRIPTION_EMBEDDING": [0.9, 0.1, 0.1, 0.1],
}

使用分区键

在 Azure Cosmos DB for NoSQL 连接器中,分区键属性默认设置为键属性 - idAzureCosmosDBNoSQLVectorStoreRecordCollectionOptions<TRecord> 类中的 PartitionKeyPropertyName 属性允许将其他属性指定为分区键。

AzureCosmosDBNoSQLVectorStoreRecordCollection 类支持两种键类型:stringAzureCosmosDBNoSQLCompositeKeyAzureCosmosDBNoSQLCompositeKeyRecordKeyPartitionKey组成。

如果未设置分区键属性(并使用默认键属性),string 键可用于使用数据库记录的操作。 但是,如果指定了分区键属性,建议使用 AzureCosmosDBNoSQLCompositeKey 来提供键值和分区键值。

指定分区键属性名称:

var options = new AzureCosmosDBNoSQLVectorStoreRecordCollectionOptions<Hotel>
{
    PartitionKeyPropertyName = nameof(Hotel.HotelName)
};

var collection = new AzureCosmosDBNoSQLVectorStoreRecordCollection<Hotel>(database, "collection-name", options) 
    as IVectorStoreRecordCollection<AzureCosmosDBNoSQLCompositeKey, Hotel>;

使用分区键获取:

var record = await collection.GetAsync(new AzureCosmosDBNoSQLCompositeKey("hotel-id", "hotel-name"));

即将推出

更多信息即将推出。

即将推出

更多信息即将推出。