|
| 1 | +package com.team_nebula.nebula.domain.star.search.batch; |
| 2 | + |
| 3 | +import org.opensearch.client.opensearch.OpenSearchClient; |
| 4 | +import org.opensearch.client.opensearch.core.BulkRequest; |
| 5 | +import org.opensearch.client.opensearch.core.BulkResponse; |
| 6 | +import org.opensearch.client.opensearch.core.bulk.IndexOperation; |
| 7 | +import com.google.common.collect.Lists; |
| 8 | +import com.team_nebula.nebula.domain.star.search.document.StarSearchDocument; |
| 9 | +import lombok.RequiredArgsConstructor; |
| 10 | +import lombok.extern.slf4j.Slf4j; |
| 11 | +import org.springframework.scheduling.annotation.Async; |
| 12 | +import org.springframework.stereotype.Service; |
| 13 | + |
| 14 | +import java.util.List; |
| 15 | +import java.util.concurrent.CompletableFuture; |
| 16 | + |
| 17 | +@Service |
| 18 | +@RequiredArgsConstructor |
| 19 | +@Slf4j |
| 20 | +public class ElasticsearchBatchService { |
| 21 | + |
| 22 | + private final OpenSearchClient openSearchClient; |
| 23 | + |
| 24 | + @Async("batchExecutor") |
| 25 | + public CompletableFuture<Void> processBatchAsync(List<StarSearchDocument> documents) { |
| 26 | + try { |
| 27 | + batchIndexDocuments(documents); |
| 28 | + return CompletableFuture.completedFuture(null); |
| 29 | + } catch (Exception e) { |
| 30 | + log.error("Async batch processing failed", e); |
| 31 | + return CompletableFuture.failedFuture(e); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public void batchIndexDocuments(List<StarSearchDocument> documents) { |
| 36 | + if (documents.isEmpty()) return; |
| 37 | + |
| 38 | + try { |
| 39 | + List<List<StarSearchDocument>> batches = Lists.partition(documents, 100); |
| 40 | + for (List<StarSearchDocument> batch : batches) { |
| 41 | + processBatch(batch); |
| 42 | + Thread.sleep(50); |
| 43 | + } |
| 44 | + } catch (Exception e) { |
| 45 | + log.error("Batch indexing failed", e); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + private void processBatch(List<StarSearchDocument> batch) throws Exception { |
| 50 | + BulkRequest.Builder bulkBuilder = new BulkRequest.Builder(); |
| 51 | + for (StarSearchDocument doc : batch) { |
| 52 | + bulkBuilder.operations(op -> op |
| 53 | + .index(IndexOperation.of(i -> i |
| 54 | + .index("star_search") |
| 55 | + .id(doc.getId()) |
| 56 | + .document(doc) |
| 57 | + )) |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + BulkResponse response = openSearchClient.bulk(bulkBuilder.build()); |
| 62 | + if (response.errors()) { |
| 63 | + log.error("Bulk indexing failed for some documents in batch"); |
| 64 | + response.items().forEach(item -> { |
| 65 | + if (item.error() != null) { |
| 66 | + log.error("Failed to index document {}: {}", item.id(), item.error().reason()); |
| 67 | + } |
| 68 | + }); |
| 69 | + } else { |
| 70 | + log.info("Successfully indexed {} documents", batch.size()); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments