@@ -316,6 +316,58 @@ def save_record(self, instance, update_fields=None, **kwargs):
316
316
logger .warning ('%s FROM %s NOT SAVED: %s' , obj ['objectID' ],
317
317
self .model , e )
318
318
319
+ def save_records (self , qs , batch_size = 1000 , ** kwargs ):
320
+ """Saves multiple records to the index in batches.
321
+
322
+ Parameters:
323
+ - qs (QuerySet): A set of records to be saved.
324
+ - batch_size (int): The size of each batch for saving records. Defaults to 1000.
325
+ - **kwargs: Additional keyword arguments.
326
+ """
327
+ self .__tmp_index .clear_objects ()
328
+ logger .debug ('CLEAR INDEX %s_tmp' , self .index_name )
329
+
330
+ to_update_batch = []
331
+ to_delete_batch = []
332
+ for instance in qs :
333
+ if not self ._should_index (instance ):
334
+ # Should not index, but since we don't know the state of the
335
+ # instance, we need to send a DELETE request.
336
+ to_delete_batch .append (instance )
337
+ continue
338
+
339
+ to_update_batch .append (self .get_raw_record (instance ))
340
+ if len (to_update_batch ) >= batch_size :
341
+ self .__tmp_index .save_objects (to_update_batch )
342
+ logger .info (
343
+ 'SAVE %d OBJECTS TO %s_tmp' , len (to_update_batch ), self .index_name
344
+ )
345
+ to_update_batch = []
346
+
347
+ if len (to_update_batch ) > 0 :
348
+ self .__tmp_index .save_objects (to_update_batch )
349
+ logger .info (
350
+ 'SAVE %d OBJECTS TO %s_tmp' , len (to_update_batch ), self .index_name
351
+ )
352
+
353
+ self .__client .move_index (self .tmp_index_name , self .index_name )
354
+ logger .info ('MOVE INDEX %s_tmp TO %s' , self .index_name , self .index_name )
355
+
356
+ if len (to_delete_batch ) > 0 :
357
+ self .delete_records (to_delete_batch )
358
+
359
+ def delete_records (self , objects ):
360
+ """Delete multiple records."""
361
+ objectIDs = [self .objectID (instance ) for instance in objects ]
362
+ try :
363
+ self .__index .delete_objects (object_ids = objectIDs )
364
+ logger .info ('DELETE %s FROM %s' , objectIDs , self .model )
365
+ except AlgoliaException as e :
366
+ if DEBUG :
367
+ raise e
368
+ else :
369
+ logger .warning ('%s FROM %s NOT DELETED: %s' , objectIDs , self .model , e )
370
+
319
371
def delete_record (self , instance ):
320
372
"""Deletes the record."""
321
373
objectID = self .objectID (instance )
0 commit comments