共用方式為


向量搜尋

Azure Cosmos DB 現在提供向量相似性搜尋的支援。 向量搜尋是某些應用程式類型的基本部分,包括 AI、語意搜尋等。 Azure Cosmos DB 可讓您將向量直接儲存在文件的其餘數據中,這表示您可以針對單一資料庫執行所有查詢。 這可大幅簡化您的架構,並移除堆疊中額外專用向量資料庫解決方案的需求。 若要深入瞭解 Azure Cosmos DB 向量搜尋, 請參閱檔

您可以在 內設定 OnModelCreating向量屬性:

public class Blog
{
    ...

    public float[] Vector { get; set; }
}

public class BloggingContext
{
    ...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>(b =>
        {
            b.Property(b => b.Vector).IsVectorProperty(DistanceFunction.Cosine, dimensions: 1536);
            b.HasIndex(x => x.Vector).IsVectorIndex(VectorIndexType.Flat);
        });
    }
}

此時您的模型已完成設定。 使用 EF 插入向量資料的方式,就和任何其他資料類型一樣:

float[] vector = /* generate vector data from text, image, etc. */
context.Add(new Blog { Vector = vector });
await context.SaveChangesAsync();

最後,在 LINQ 查詢使用 EF.Functions.VectorDistance() 函式執行向量相似性搜尋:

float[] anotherVector = /* generate vector data from text, image, etc. */
var blogs = await context.Blogs
    .OrderBy(s => EF.Functions.VectorDistance(s.Vector, anotherVector))
    .Take(5)
    .ToListAsync();

它會根據其 Vector 屬性的相似性和外部提供的 anotherVector 資料,傳回前五個部落格。

向量相似度搜尋可以搭配相同查詢中的全文搜索使用(亦即混合式搜尋),方法是使用VectorDistance(倒數排名融合)函式來結合FullTextScore函式和RRF函式的結果。

請參閱 以瞭解如何在 EF 模型中啟用全文搜索支援,以及如何在查詢中使用混合式搜尋。