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

3

不需要过多的背景,这是我的问题:

为了使用.NET SDK在C#中创建一个新的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*");

将返回所有以“cheap”开头的字符串文档,但我需要类似于string.Contains()的功能,或者至少需要后缀搜索。我正在尝试做一些像

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

要获取包含字符串“heap”的所有结果,不论其位置。我知道可以使用自定义分析器来实现这一点,但这些分析器只能通过Azure Search REST API创建和应用,并且仅在索引创建时可以使用。这使得我提供的几乎所有内容都无法使用,因为我必须通过Postman和SDK以JSON格式定义我的“Hotels”索引、字段和分析器,而SDK仅适用于查询。这也意味着我需要在每个索引中重复定义相同的自定义分析器,因为Azure Search似乎不支持全局分析器定义。

因此,问题是:有没有办法在C#中定义一个自定义分析器,我可以在创建索引时引用和应用它?或者说,有没有一种简单的方法只使用.NET SDK就能获得完整的通配符支持?

1个回答

5
你可以这样做:
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; }

请参考Azure Search中的自定义分析器博客文章以及API单元测试CustomAnalyzerTests,了解更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接