Azure 搜索 CreateIndexAsync 因 CamelCase 字段名称 FieldBuilder 失败

问题描述

Azure 搜索 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);
     }
}

解决方法

有关 FieldBuilder,请参阅 our sample。基本上,您必须对 FieldBuilderSearchClient 使用命名策略:

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

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