33using Azure . Search . Documents . Models ;
44using System ;
55using System . Collections . Generic ;
6+ using System . Linq ;
67using System . Threading . Tasks ;
78
89namespace OptimizeDataIndexing
@@ -14,6 +15,8 @@ private static async Task<IndexDocumentsResult> ExponentialBackoffAsync(SearchCl
1415 {
1516 // Create batch of documents for indexing
1617 var batch = IndexDocumentsBatch . Upload ( hotels ) ;
18+
19+ // Create an object to hold the result
1720 IndexDocumentsResult result = null ;
1821
1922 // Define parameters for exponential backoff
@@ -28,12 +31,43 @@ private static async Task<IndexDocumentsResult> ExponentialBackoffAsync(SearchCl
2831 {
2932 attempts ++ ;
3033 result = await searchClient . IndexDocumentsAsync ( batch ) . ConfigureAwait ( false ) ;
34+
35+ var failedDocuments = result . Results . Where ( r => r . Succeeded != true ) . ToList ( ) ;
36+
37+ // handle partial failure
38+ if ( failedDocuments . Count > 0 )
39+ {
40+
41+ if ( attempts == maxRetryAttempts )
42+ {
43+ Console . WriteLine ( "[MAX RETRIES HIT] - Giving up on the batch starting at {0}" , id ) ;
44+ break ;
45+ }
46+ else
47+ {
48+ Console . WriteLine ( "[Batch starting at doc {0} had partial failure]" , id ) ;
49+ //Console.WriteLine("[Attempt: {0} of {1} Failed]", attempts, maxRetryAttempts);
50+ Console . WriteLine ( "[Retrying {0} failed documents] \n " , failedDocuments . Count ) ;
51+
52+ // creating a batch of failed documents to retry
53+ var failedDocumentKeys = failedDocuments . Select ( doc => doc . Key ) . ToList ( ) ;
54+ hotels = hotels . Where ( h => failedDocumentKeys . Contains ( h . HotelId ) ) . ToList ( ) ;
55+ batch = IndexDocumentsBatch . Upload ( hotels ) ;
56+
57+ Task . Delay ( delay ) . Wait ( ) ;
58+ delay = delay * 2 ;
59+ continue ;
60+ }
61+ }
62+
63+
3164 return result ;
3265 }
3366 catch ( RequestFailedException ex )
3467 {
35- Console . WriteLine ( "BATCH STARTING AT DOC {0}:" , id ) ;
36- Console . WriteLine ( "[Attempt: {0} of {1} Failed] - Error: {2} \n " , attempts , maxRetryAttempts , ex . Message ) ;
68+ Console . WriteLine ( "[Batch starting at doc {0} failed]" , id ) ;
69+ //Console.WriteLine("[Attempt: {0} of {1} Failed] - Error: {2} \n", attempts, maxRetryAttempts, ex.Message);
70+ Console . WriteLine ( "[Retrying entire batch] \n " ) ;
3771
3872 if ( attempts == maxRetryAttempts )
3973 {
0 commit comments