Search code examples
azure-cognitive-searchazure-search-.net-sdk

Azure Search RetryPolicy


We are using azure search and need to implement a retry stratgey as well as storing the Ids of failed documents as described.

Is there any documentation/samples on how to implement a RetryPolicy strategy in Azure Search.

Thanks


Solution

  • This is what I used:

     private async Task<DocumentIndexResult> IndexWithExponentialBackoffAsync(IndexBatch<IndexModel> indexBatch)
     {
          return await Policy
               .Handle<IndexBatchException>()
               .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, span) =>
               {
                    indexBatch = ((IndexBatchException)ex).FindFailedActionsToRetry(indexBatch, x => x.Id);
               })
               .ExecuteAsync(async () => await _searchClient.IndexAsync(indexBatch));
     }
    

    It uses the Polly library to handle exponential backoff. In this case I use a model IndexModel that has a id field named Id. If you like to log or store the ids of the failed attempts you can do that in the WaitAndRetryAsync function like

    ((IndexBatchException)ex)ex.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key).<Do something here>