Microsoft.Extensions.VectorData 라이브러리는 벡터 저장소 추상화의 일부로 벡터 검색 기능을 제공합니다. 이러한 기능에는 필터링 및 기타 많은 옵션이 포함되며,
벡터 검색
이 메서드는 SearchAsync 유사성 검색을 수행하여 벡터 속성이 지정된 값과 가장 유사한 레코드를 반환합니다. 이미 데이터가 포함된 컬렉션이 있다고 가정하면 Qdrant를 사용한 벡터 검색을 보여 주는 최소 샘플은 다음과 같습니다.
// Create a Qdrant VectorStore object and get a VectorStoreCollection for a collection that already contains records
VectorStore vectorStore = new QdrantVectorStore(new QdrantClient("localhost"), ownsClient: true);
VectorStoreCollection<ulong, Hotel> collection = vectorStore.GetCollection<ulong, Hotel>("skhotels");
// Get the 3 hotels whose vector property is most similar to the query text
IAsyncEnumerable<VectorSearchResult<Hotel>> results = collection.SearchAsync("Big rooms with a view", top: 3);
// Inspect the returned hotels and their similarity scores
await foreach (VectorSearchResult<Hotel> record in results)
{
Console.WriteLine("Found hotel description: " + record.Record.Description);
Console.WriteLine("Found record score: " + record.Score);
}
생성 임베딩에 대한 자세한 내용은 Vector 속성 및 임베딩 생성을 참조하세요.
결과 수 및 건너뛰기 결과
SearchAsync 에는 검색에서 반환된 최대 레코드 수를 제어하는 필수 top 매개 변수가 있습니다. 오버페치하면 애플리케이션 성능이 저하될 수 있으므로 항상 실제로 필요한 상위 레코드 수를 고려합니다.
IAsyncEnumerable<VectorSearchResult<Hotel>> searchResult = collection.SearchAsync("Big rooms with a view", top: 3);
또한 필요에 따라 레코드를 건너뛸 수 있습니다. 예를 들어 다음 검색에서는 40을 건너뛴 후 가장 관련성이 큰 20개의 제품을 반환합니다.
IAsyncEnumerable<VectorSearchResult<Product>> results = collection.SearchAsync(
"Green socks",
top: 20,
new() { Skip = 40 });
top 및 Skip은 별도의 호출을 통해 다수의 결과를 검색하기 위해 페이징을 수행하는 데 사용할 수 있습니다. 그러나 건너뛴 레코드를 찾고 처리해야 하므로 이 기술은 데이터베이스에서 잘 수행되지 않을 수 있습니다. 자세한 내용은 데이터베이스 설명서를 참조하세요.
메타데이터 필터링
VectorSearchOptions<TRecord>.Filter 벡터 검색을 적용하기 전에 선택한 컬렉션의 레코드를 필터링하는 옵션을 사용합니다. 여기에는 다음과 같은 여러 가지 이점이 있습니다.
- 필터링 후 남은 레코드만 검색 벡터와 비교해야 하므로 더 적은 벡터 비교를 수행해야 하므로 대기 시간 및 처리 비용이 줄어듭니다.
- 결과 집합을 제한합니다. 예를 들어 사용자가 액세스 권한이 없어야 하는 데이터를 제외하거나 특정 제품 범주 내에서만 검색하여 액세스 제어를 구현할 수 있습니다.
필터링에 사용할 필드의 경우 많은 벡터 저장소에서 해당 필드를 먼저 인덱싱해야 합니다. 데이터 속성에서 인덱싱을 사용하도록 설정하는 방법에 대한 자세한 내용은 데이터 속성을 참조하세요.
필터는 데이터 모델의 형식에 따라 LINQ 식을 사용하여 표현됩니다. 지원되는 LINQ 식 집합은 각 데이터베이스에서 지원하는 기능에 따라 다르지만, 모든 데이터베이스는 같음, 같지 않음 및 같은 광범위한 공통 식 기반을 지원합니다andor.
class Glossary
{
// ...
// Category is marked as indexed, since you want to filter using this property.
[VectorStoreData(IsIndexed = true)]
public required string Category { get; set; }
// Tags is marked as indexed, since you want to filter using this property.
[VectorStoreData(IsIndexed = true)]
public required List<string> Tags { get; set; }
}
IAsyncEnumerable<VectorSearchResult<Glossary>> results = collection.SearchAsync(
"Some term",
top: 3,
new()
{
Filter = r => r.Category == "External Definitions" && r.Tags.Contains("memory")
});
결과에 벡터 포함
기본적으로 벡터 속성은 검색 결과에 포함되지 않으므로 데이터 전송이 줄어듭니다. 검색 설정에서 그것들을 포함하도록 구성할 수 있습니다.
IAsyncEnumerable<VectorSearchResult<Product>> results = collection.SearchAsync(
"Green socks",
top: 3,
new() { IncludeVectors = true });
벡터 속성 지정
대부분의 시나리오에서는 데이터 모델에 단일 벡터 속성만 정의되어 있으며, SearchAsync은/는 자동으로 해당 속성을 검색합니다. 그러나 여러 벡터 속성이 정의되면 사용할 벡터 속성을 지정해야 합니다.
class Product
{
// ...
// Multiple vector properties:
[VectorStoreVector(1536)]
public ReadOnlyMemory<float> DescriptionEmbedding { get; set; }
[VectorStoreVector(1536)]
public ReadOnlyMemory<float> FeatureListEmbedding { get; set; }
}
IAsyncEnumerable<VectorSearchResult<Hotel>> results = collection.SearchAsync(
"I'm looking for a product with a specific feature.",
top: 3,
new() { VectorProperty = r => r.FeatureListEmbedding });
하이브리드 검색
하이브리드 검색은 벡터 유사성 검색을 기존 키워드 검색과 결합하여 병렬로 실행하고 두 결과 집합의 조합을 반환합니다. 키워드 일치는 벡터 유사성이 누락될 수 있는 정확한 용어 일치를 캡처할 수 있고 그 반대의 경우도 마찬가지이므로 검색 품질을 향상시킬 수 있습니다.
메모
하이브리드 검색은 해당 검색을 지원하는 데이터베이스에서만 사용할 수 있습니다. 이러한 데이터베이스에 대한 공급자만 인터페이스를 구현합니다 IKeywordHybridSearchable<TRecord> .
하이브리드 검색을 사용하려면 데이터 모델에 다음을 통해 IsFullTextIndexed전체 텍스트 검색을 사용하도록 설정된 문자열 필드가 필요합니다.
class Hotel
{
[VectorStoreKey]
public ulong Key { get; set; }
[VectorStoreData(IsFullTextIndexed = true)]
public required string Description { get; set; }
[VectorStoreVector(1536)]
public string DescriptionEmbedding { get; set; }
}
그런 다음 검색 텍스트와 키워드를 모두 전달하여 호출 HybridSearchAsync합니다.
var hybridCollection = (IKeywordHybridSearchable<Hotel>)collection;
IAsyncEnumerable<VectorSearchResult<Hotel>> results = hybridCollection.HybridSearchAsync(
"I'm looking for a hotel where customer happiness is the priority.",
["happiness", "hotel", "customer"],
top: 3);
벡터 검색에 대해 설명된 모든 옵션(top, Skip, Filter, IncludeVectors, VectorProperty)은 하이브리드 검색 HybridSearchOptions<TRecord>에도 사용할 수 있습니다.
또한 하이브리드 검색은 AdditionalProperty 대상으로 지정할 전체 텍스트 검색 속성을 지정하는 옵션을 지원합니다. 데이터 모델에 속성 IsFullTextIndexed = true이 하나만 있는 경우 자동으로 사용됩니다. 여러 속성이 있는 경우 다음 중 하나를 지정해야 합니다.
IAsyncEnumerable<VectorSearchResult<Hotel>> results = hybridCollection.HybridSearchAsync(
"I'm looking for a hotel where customer happiness is the priority.",
["happiness", "hotel", "customer"],
top: 3,
new()
{
VectorProperty = r => r.DescriptionEmbedding,
AdditionalProperty = r => r.Description
});
.NET