Azure搜索.net SDK-如何使用"FindFailedActionsToRetry"?

ric*_*ard 5 azure azure-cognitive-search azure-search-.net-sdk

使用Azure搜索.net SDK,当您尝试索引文档时,可能会出现异常IndexBatchException.

从这里的文档:

        try
        {
            var batch = IndexBatch.Upload(documents);
            indexClient.Documents.Index(batch);
        }
        catch (IndexBatchException e)
        {
            // Sometimes when your Search service is under load, indexing will fail for some of the documents in
            // the batch. Depending on your application, you can take compensating actions like delaying and
            // retrying. For this simple demo, we just log the failed document keys and continue.
            Console.WriteLine(
                "Failed to index some of the documents: {0}",
                String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));
        }
Run Code Online (Sandbox Code Playgroud)

如何使用e.FindFailedActionsToRetry创建新批处理以重试失败操作的索引?

我创建了一个这样的函数:

    public void UploadDocuments<T>(SearchIndexClient searchIndexClient, IndexBatch<T> batch, int count) where T : class, IMyAppSearchDocument
    {
        try
        {
            searchIndexClient.Documents.Index(batch);
        }
        catch (IndexBatchException e)
        {
            if (count == 5) //we will try to index 5 times and give up if it still doesn't work.
            {
                throw new Exception("IndexBatchException: Indexing Failed for some documents.");
            }

            Thread.Sleep(5000); //we got an error, wait 5 seconds and try again (in case it's an intermitent or network issue

            var retryBatch = e.FindFailedActionsToRetry<T>(batch, arg => arg.ToString());
            UploadDocuments(searchIndexClient, retryBatch, count++);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我认为这部分是错误的:

var retryBatch = e.FindFailedActionsToRetry<T>(batch, arg => arg.ToString());
Run Code Online (Sandbox Code Playgroud)

Bru*_*ton 5

FindFailedActionsToRetry名为的第二个参数keySelector是一个函数,它应返回模型类型上的任何属性表示文档键.在您的示例中,您的模型类型在内部编译时是未知的UploadDocuments,因此您需要更改UploadsDocuments为也接受keySelector参数并将其传递给FindFailedActionsToRetry.调用者UploadDocuments需要指定特定于类型的lambda T.例如,如果T本文中Hotel示例代码中的示例类,则lambda必须是因为它的属性用作文档键.hotel => hotel.HotelIdHotelIdHotel

顺便说一句,catch块内的等待不应该等待一段时间.如果你的搜索服务负载很重,等待一个持续的延迟将无助于给它时间恢复.相反,我们建议指数后退(例如 - 第一个延迟是2秒,然后是4秒,然后是8秒,然后是16秒,最多到某个最大值).

  • 只要您取得进展,您就可以继续重试(批次中的项目少于上次 Index 调用时的项目),并且仅在您没有取得进展时限制重试次数。在这种情况下,最大重试次数应基于您愿意等待多长时间,因为延迟呈指数增长。超过某个点后,您可以从指数延迟切换到恒定延迟(例如,在延迟达到几分钟后,或者您发现任何适合您的延迟)。 (2认同)