Azure 搜索 v11:索引复杂类型的可为 null 的集合

Azure Search v11: Indexing nullable Collection of Complex Type

我正在将 Azure 认知搜索 服务的 SDK 从 v10 更新到 v11。我已按照指南中的所有步骤进行升级,但是我注意到索引(合并或上传)操作有一个奇怪的行为:UploadDocumentAsync(但也使用其他方法索引数据)当 Collection (Edm.ComplexType) 类型的 属性 为 null 时操作失败,并出现以下错误:

在尝试读取 属性 的内容时,从 JSON reader 中读取了类型 'PrimitiveValue' 的节点。但是,需要一个 'StartArray' 节点 json。

IndexDocumentsResult response = await searchClient.UploadDocumentsAsync<T>(documents).ConfigureAwait (false);

v10 没有出现这个问题。我找到的解决方法是将集合设置为空数组而不是空值,但我想找到更好的解决方案。

已编辑: 我从 Microsoft.Azure.Search v10.1.0 升级到 Azure.Search.Documents v11.1.1 以下是用于索引数据的通用 T class 示例:

public class IndexEntity
{
    [JsonProperty("@search.score")]
    public double SearchScore { get; set; }

    [JsonProperty("Key")]
    public Guid Id { get; set; }

    [JsonProperty("Code")]
    public string Code { get; set; }

    [JsonProperty("ComplexObj")]
    public ComplexType[] CollectionOfComplexType{ get; set; }

}

遵循 ModelObjectToIndex 的定义

public class ComplexType
{
    [JsonProperty("Id")]
    public string Id { get; set; }

    [JsonProperty("Value")]
    public string Value { get; set; }
}

基本上当 CollectionOfComplexType 属性 为空时,我会收到上述错误。如果我将它设置为一个空数组,则不会发生错误,但如前所述,我不喜欢这个解决方案,而且在旧版本中它是允许的操作(索引已成功完成)

我们的Azure.Search.Documents行为在这方面似乎有所改变。我已经打开 https://github.com/Azure/azure-sdk-for-net/issues/18169 来跟踪分辨率。

您可以通过传入一个 JsonSerializerSettings 来解决这个问题,而无需将您的集合初始化为空数组,这与我们在旧的 Microsoft.Azure.Search 库中所做的类似,因为它似乎来自使用JsonPropertyAttribute 你正在使用 Newtonsoft.Json(又名 Json.NET):

  1. 如果您还没有,请添加对 Microsoft.Azure.Core.NewtonsoftJson 的包引用。它最近 GA'd 所以你不需要使用预览,我想这是因为 System.Text.Json - 我们的默认序列化器 - 不会尊重你的 属性 重命名。

  2. 在创建 SearchClient 之前传入 JsonSerializerSettings,如下所示:

    var settings = new JsonSerializerSettings
    {
        // Customize anything else you want here; otherwise, defaults are used.
        NullValueHandling = NullValueHandling.Ignore,
    };
    
    var options = new SearchClientOptions
    {
        Serializer = new NewtonsoftJsonObjectSerializer(settings),
    };
    
    var searchClient = new SearchClient(options);
    

如果可以的话,我们将讨论如何默认解决此问题。与旧库相比的一大变化是能够自定义所使用的序列化程序。默认情况下,我们使用 System.Text.Json,但我们支持其他序列化程序,包括 Newtonsoft.Json。如果有人要传递他们自己的设置 - 或者甚至想要默认设置 - 更改可能是灾难性的。所以我很好奇:如果我们至少记录了这种行为变化(也许在 SearchClient class 评论 and/or UploadDocuments 和相关方法上)以及如何保留以前的行为,那会有帮助还是令人满意?