注释
EF 10 中引入了对 Cosmos 的全文搜索支持。
Azure Cosmos DB 现在支持 全文搜索。 它使用词干分析等高级技术实现高效有效的文本搜索,以及评估文档与给定搜索查询的相关性。 它可以与矢量搜索(即混合搜索)结合使用,以提高某些 AI 方案中响应的准确性。 EF Core 允许使用启用了全文搜索的属性对数据库进行建模,并在面向 Azure Cosmos DB 的查询中使用全文搜索函数。
模型配置
可以在 OnModelCreating 内配置属性,通过为该属性启用全文搜索并定义全文索引。
public class Blog
{
...
public string Contents { get; set; }
}
public class BloggingContext
{
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>(b =>
{
b.Property(x => x.Contents).EnableFullTextSearch();
b.HasIndex(x => x.Contents).IsFullTextIndex();
});
}
}
注释
配置索引不是强制性的,但建议这样做,因为它极大地提高了全文搜索查询的性能。
全文搜索作是特定于语言的,默认情况下使用美国英语(en-US)。 可以在调用过程中 EnableFullTextSearch 自定义各个属性的语言:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>(b =>
{
b.Property(x => x.Contents).EnableFullTextSearch();
b.HasIndex(x => x.Contents).IsFullTextIndex();
b.Property(x => x.ContentsGerman).EnableFullTextSearch("de-DE");
b.HasIndex(x => x.ContentsGerman).IsFullTextIndex();
});
}
您还可以为容器设置默认语言 —— 除非在 EnableFullTextSearch 方法中进行了重写,否则容器中的所有全文属性都将使用该默认语言。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>(b =>
{
b.HasDefaultFullTextLanguage("de-DE");
b.Property(x => x.ContentsEnglish).EnableFullTextSearch("en-US");
b.HasIndex(x => x.ContentsEnglish).IsFullTextIndex();
b.Property(x => x.ContentsGerman).EnableFullTextSearch();
b.HasIndex(x => x.ContentsGerman).IsFullTextIndex();
b.Property(x => x.TagsGerman).EnableFullTextSearch();
b.HasIndex(x => x.TagsGerman).IsFullTextIndex();
});
}
查询
作为全文搜索功能的一部分,Azure Cosmos DB 引入了多个内置函数,允许高效查询已启用全文搜索的属性内的内容。 这些函数包括: FullTextContains、 FullTextContainsAll、 FullTextContainsAny查找特定关键字或关键字,并根据 FullTextScore提供的关键字返回 BM25 分数 。
注释
FullTextScore 只能在 OrderBy 内使用,以根据分数对文档进行排名。
EF Core 将这些函数公开为其中的一部分 EF.Functions ,以便在查询中使用它们:
var cosmosBlogs = await context.Blogs.Where(x => EF.Functions.FullTextContainsAll(x.Contents, "database", "cosmos")).ToListAsync();
var keywords = new string[] { "AI", "agent", "breakthrough" };
var mostInteresting = await context.Blogs.OrderBy(x => EF.Functions.FullTextScore(x.Contents, keywords)).Take(5).ToListAsync();
混合搜索
全文搜索可用于同一查询中的 矢量搜索 ;这有时称为“混合搜索”,涉及通过 RRF(倒数排名融合)函数合并来自多个搜索的评分结果。 正确设置矢量和全文搜索配置后,可以按如下所示执行混合搜索:
float[] myVector = /* generate vector data from text, image, etc. */
var hybrid = await context.Blogs
.OrderBy(x => EF.Functions.Rrf(
EF.Functions.FullTextScore(x.Contents, "database"),
EF.Functions.VectorDistance(x.Vector, myVector)))
.Take(10)
.ToListAsync();
RRF 函数还允许为每个搜索函数分配不同的权重,从而允许矢量搜索在总体结果中具有很大的权重:
float[] myVector = /* generate vector data from text, image, etc. */
var hybrid = await context.Blogs
.OrderBy(x => EF.Functions.Rrf(
new[]
{
EF.Functions.FullTextScore(x.Contents, "database"),
EF.Functions.VectorDistance(x.Vector, myVector)
},
weights: new[] { 1, 2 }))
.Take(10)
.ToListAsync();
小窍门
可以在调用中 Rrf 合并两个以上的评分函数,以及仅 FullTextScore使用或仅 VectorDistance 调用。