首页 > 解决方案 > Azure 搜索 CreateIndexAsync 失败并出现 CamelCase 字段名称 FieldBuilder

问题描述

Azure Search V11
我无法让它工作。但是使用标准 FieldBuilder 会创建索引。

private static async Task CreateIndexAsync(SearchIndexClient indexClient, string indexName, Type type)
{
    var builder = new FieldBuilder
    {
        Serializer = new JsonObjectSerializer(new JsonSerializerOptions {PropertyNamingPolicy = new CamelCaseNamingPolicy()})
    };
    var searchFields = builder.Build(type).ToArray();
    var definition = new SearchIndex(indexName, searchFields);

    await indexClient.CreateIndexAsync(definition);
}

`

public class CamelCaseNamingPolicy : JsonNamingPolicy
{
     public override string ConvertName(string name)
     {
         return char.ToLower(name[0]) + name.Substring(1);
     }
}

标签: azure-search-.net-sdk

解决方案


请参阅我们的示例FieldBuilder基本上,您必须为FieldBuilder和使用命名策略SearchClient

var clientOptions = new SearchClientOptions
{
  Serializer = new JsonObjectSerializer(
    new JsonSerializerOptions
    {
      PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    }),
};

var builder = new FieldBuilder
{
  Serializer = clientOptions.Serializer,
};

var index = new SearchIndex("name")
{
  Fields = builder.Build(type),
};

var indexClient = new SearchIndexClient(uri, clientOptions);

await indexClient.CreateIndexAsync(index);
await Task.DelayAsync(5000); // can take a little while

var searchClient = new SearchClient(uri, clientOptions);
var response = await searchClient.SearchAsync("whatever");

虽然此示例有效(我们的示例代码来自经常执行的测试),但如果您还有其他问题,请务必发布您收到的确切异常消息。


推荐阅读