首页 > 解决方案 > Azure 搜索:为复杂类型创建索引

问题描述

我有一个包含一些 xml 文件的 blob 存储。我想使用 Azure 搜索的强大功能在此 Blob 存储中轻松查找文档。XML 文件的结构采用以下格式:

<items>
    <item>
        <id>12345</id>
        <text>This is an example</text>
    <item>
    <item>
        <id>12346</id>
        <text>This is an example</text>
    <item>
</items>

在 Azure 搜索中创建索引失败,因为索引需要将字段标记为IsKey顶级,但我没有这样的字段。我该如何解决这个问题?下面是为 ComplexTypes 生成索引的代码:

var complexField = new ComplexField("items");
complexField.Fields.Add(new SearchableField("id") { IsKey = true, IsFilterable = true, IsSortable = true });
complexField.Fields.Add(new SearchableField("text") { IsFilterable = true, IsSortable = true });

var index = new SearchIndex(IndexName)
{
    Fields =
    {
        complexField
    }
};

谁能指导我正确的方向?

标签: c#azureazure-cognitive-searchazure-search-.net-sdk

解决方案


我建议使用类来创建索引。

例如:

using Microsoft.Azure.Search;
using System.ComponentModel.DataAnnotations;

namespace Test
{
    public class Records
    {
        [Key]
        [IsSortable, IsFilterable]
        public string id { get; set; }

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

然后使用以下内容创建它:

var _serviceClient = new SearchServiceClient("<ServiceName>", new SearchCredentials("<ApiKey">));

public bool Create()
{
    var newIndex = new Microsoft.Azure.Search.Models.Index()
    {
        Name = "<Index_Name>",
        Fields = FieldBuilder.BuildForType<Records>()
    };
    _serviceClient.Indexes.Create(newIndex);
}

推荐阅读