다음을 통해 공유


Azure CosmosDB NoSQL Vector Store 커넥터 사용(미리 보기)

Warning

의미 체계 커널 벡터 저장소 기능은 미리 보기 상태이며 릴리스 전에 제한된 상황에서도 호환성이 손상되는 변경이 필요한 개선 사항이 계속 발생할 수 있습니다.

개요

Azure CosmosDB NoSQL 벡터 저장소 커넥터를 사용하여 Azure CosmosDB NoSQL의 데이터에 액세스하고 관리할 수 있습니다. 커넥터의 특징은 다음과 같습니다.

기능 영역 지원
컬렉션이 다음으로 매핑됩니다. Azure Cosmos DB NoSQL 컨테이너
지원되는 키 속성 형식
  • string
  • AzureCosmosDBNoSQLCompositeKey
지원되는 데이터 속성 형식
  • string
  • int
  • long
  • double
  • float
  • bool
  • DateTimeOffset
  • 이러한 각 형식의 열거형 및 열거형
지원되는 벡터 속성 형식
  • ReadOnlyMemory<float>
  • ReadOnlyMemory<바이트>
  • ReadOnlyMemory<sbyte>
  • ReadOnlyMemory<절반>
지원되는 인덱스 형식
  • 플랫
  • QuantizedFlat
  • DiskAnn
지원되는 거리 함수
  • CosineSimilarity
  • DotProductSimilarity
  • EuclideanDistance
지원되는 필터 절
  • AnyTagEqualTo
  • EqualTo
레코드에서 여러 벡터를 지원합니다.
IsFilterable이 지원되는가요?
IsFullTextSearchable이 지원되나요?
StoragePropertyName이 지원되는가요? 아니요, 대신 사용합니다 JsonSerializerOptionsJsonPropertyNameAttribute . 자세한 내용은 여기를 참조하세요.

제한

CosmosClient 수동으로 초기화하는 경우 기본 serializer의 제한으로 인해 CosmosClientOptions.UseSystemTextJsonSerializerWithOptions 지정해야 합니다. 이 옵션은 특정 구성 요구 사항을 충족하도록 JsonSerializerOptions.Default 설정하거나 다른 serializer 옵션으로 사용자 지정할 수 있습니다.

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 Vector Store 인스턴스를 직접 생성할 수 있습니다.

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 , 데이터 모델 속성 이름과 다른 스토리지 이름이 필요한 경우 해당 사용이 지원됩니다. 유일한 예외는 모든 CosmosDB NoSQL 레코드가 ID에 이 이름을 사용해야 하므로 명명 id된 데이터베이스 필드에 매핑되는 레코드의 키입니다.

사용자 지정 속성 명명 정책과 함께 사용자 지정 JsonSerializerOptions 인스턴스를 사용할 수도 있습니다. 이를 사용하려면 on 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 });

사용 중인 위의 사용자 지정 JsonSerializerOptions 을 사용하여 SnakeCaseUpper다음 데이터 모델이 아래 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],
}

파티션 키 사용

NoSQL용 Azure Cosmos DB 커넥터에서 파티션 키 속성은 기본적으로 키 속성인 id. AzureCosmosDBNoSQLVectorStoreRecordCollectionOptions<TRecord> 클래스의 PartitionKeyPropertyName 속성을 사용하면 다른 속성을 파티션 키로 지정할 수 있습니다.

AzureCosmosDBNoSQLVectorStoreRecordCollection 클래스는 stringAzureCosmosDBNoSQLCompositeKey두 가지 키 형식을 지원합니다. AzureCosmosDBNoSQLCompositeKeyRecordKeyPartitionKey으로 구성되어 있습니다.

파티션 키 속성이 설정되지 않고 기본 키 속성이 사용되는 경우 데이터베이스 레코드가 있는 작업에 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"));

서비스 예정

추가 정보는 곧 제공될 예정입니다.

서비스 예정

추가 정보는 곧 제공될 예정입니다.