Search code examples
c#azureazure-cognitive-searchazure-search-.net-sdk

Azure Search: Create Index for complex types


I have a blob storage that contains some xml-files. I want to use the power of Azure Search to easily find documents in this blob storage. The structure of the XML-files are in this format:

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

Creating an index in Azure Search fails because the index requires marking a field as IsKey at the top level, but I don't have such a field. How can I solve this? Underneath is the code to generate an index for 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
    }
};

Can anyone guide me in the correct direction?


Solution

  • I would recommend using a Class for creating the Index.

    For example:

    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; }
        }
    }
    

    And then create it using something like the following:

    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);
    }