gpt4 book ai didi

c# - Azure 搜索 .NET SDK 自定义分析器

转载 作者:行者123 更新时间:2023-12-02 03:41:45 25 4
gpt4 key购买 nike

没有太多背景,这是我的问题:

要在 C# 中使用 .NET SDK 创建新的 Azure 搜索索引(使用文档中提供的酒店示例),我的代码如下所示:

public class Hotel
{
[System.ComponentModel.DataAnnotations.Key]
[IsFilterable]
public string HotelId { get; set; }

[IsFilterable, IsSortable, IsFacetable]
public double? BaseRate { get; set; }

[IsSearchable]
public string Description { get; set; }

[IsSearchable]
[Analyzer(AnalyzerName.AsString.FrLucene)]
[JsonProperty("description_fr")]
public string DescriptionFr { get; set; }

[IsSearchable, IsFilterable, IsSortable]
public string HotelName { get; set; }

[IsSearchable, IsFilterable, IsSortable, IsFacetable]
public string Category { get; set; }

[IsSearchable, IsFilterable, IsFacetable]
public string[] Tags { get; set; }

[IsFilterable, IsFacetable]
public bool? ParkingIncluded { get; set; }

[IsFilterable, IsFacetable]
public bool? SmokingAllowed { get; set; }

[IsFilterable, IsSortable, IsFacetable]
public DateTimeOffset? LastRenovationDate { get; set; }

[IsFilterable, IsSortable, IsFacetable]
public int? Rating { get; set; }

[IsFilterable, IsSortable]
public GeographyPoint Location { get; set; }
}

private static void CreateHotelsIndex(ISearchServiceClient serviceClient)
{
var definition = new Index
{
Name = "hotels",
Fields = FieldBuilder.BuildForType<Hotel>()
};

serviceClient.Indexes.Create(definition);
}

这很好用。

问题与使用 .NET SDK 进行搜索有关。前缀搜索工作正常

var results = indexClient.Documents.Search<Hotel>("cheap*");

将返回所有包含以“便宜”开头的字符串的文档,但我需要一种 string.Contains() 类型的功能,或者至少是后缀搜索。我正在尝试做类似的事情

var results = indexClient.Documents.Search<Hotel>("*heap*");

获取任意位置包含字符串“heap”的所有结果。

我知道有一些方法可以使用自定义分析器来执行此操作,但这些分析器只能通过 Azure 搜索 REST API 创建和应用,并且只能在创建索引时使用。这使得我上面提供的几乎所有内容都无法使用,因为我必须通过 Postman 在 JSON 中定义我的“酒店”索引、字段和分析器,而 SDK 实际上只对查询有用。这也意味着我需要在我创建的每个索引中重复定义相同的自定义分析器,因为 Azure 搜索似乎不支持全局分析器定义。

所以这里的问题是:有没有一种方法可以在 C# 中定义自定义分析器,我可以在创建索引时引用并应用于我的索引?或者,真的,是否有仅使用 .NET SDK 即可获得完整通配符支持的简单方法?

最佳答案

你可以这样做:

private static void CreateHotelsIndex(ISearchServiceClient serviceClient)
{
var definition = new Index
{
Name = "hotels",
Fields = FieldBuilder.BuildForType<Hotel>(),
Analyzers = new[]
{
new CustomAnalyzer
{
Name = "my_analyzer",
Tokenizer = TokenizerName.Standard,
TokenFilters = new[]
{
TokenFilterName.Lowercase,
TokenFilterName.AsciiFolding,
TokenFilterName.Phonetic
}
}
}
};

serviceClient.Indexes.Create(definition);
}

...然后在文档定义中引用自定义分析器:

[IsSearchable, IsFilterable, IsSortable, Analyzer("my_analyzer")]
public string HotelName { get; set; }

参见 Custom analyzers in Azure Search API 单元测试的博客文章和示例 CustomAnalyzerTests获取更多信息。

关于c# - Azure 搜索 .NET SDK 自定义分析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48408000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com