Blame view

indexer/bulk_indexer.py 6.33 KB
be52af70   tangwang   first commit
1
2
3
4
5
6
7
8
9
  """
  Bulk indexer for Elasticsearch.
  
  Handles batch indexing of documents with progress tracking and error handling.
  """
  
  from typing import List, Dict, Any, Optional
  from elasticsearch.helpers import bulk, BulkIndexError
  from utils.es_client import ESClient
d6606d7a   tangwang   清理旧代码,具体如下:
10
  from indexer.mapping_generator import DEFAULT_INDEX_NAME
be52af70   tangwang   first commit
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
  import time
  
  
  class BulkIndexer:
      """Bulk indexer for Elasticsearch with batching and error handling."""
  
      def __init__(
          self,
          es_client: ESClient,
          index_name: str,
          batch_size: int = 500,
          max_retries: int = 3
      ):
          """
          Initialize bulk indexer.
  
          Args:
              es_client: Elasticsearch client
              index_name: Target index name
              batch_size: Number of documents per batch
              max_retries: Maximum retry attempts for failed batches
          """
          self.es_client = es_client
          self.index_name = index_name
          self.batch_size = batch_size
          self.max_retries = max_retries
  
      def index_documents(
          self,
          documents: List[Dict[str, Any]],
          id_field: str = "skuId",
          show_progress: bool = True
      ) -> Dict[str, Any]:
          """
          Index documents in bulk.
  
          Args:
              documents: List of documents to index
              id_field: Field to use as document ID
              show_progress: Whether to print progress
  
          Returns:
              Dictionary with indexing statistics
          """
          total_docs = len(documents)
          success_count = 0
          failed_count = 0
          errors = []
  
          print(f"[BulkIndexer] Starting bulk indexing of {total_docs} documents...")
          start_time = time.time()
  
          # Process in batches
          for i in range(0, total_docs, self.batch_size):
              batch = documents[i:i + self.batch_size]
              batch_num = (i // self.batch_size) + 1
              total_batches = (total_docs + self.batch_size - 1) // self.batch_size
  
              if show_progress:
                  print(f"[BulkIndexer] Processing batch {batch_num}/{total_batches} "
                        f"({len(batch)} documents)...")
  
              # Prepare actions for bulk API
              actions = []
              for doc in batch:
                  action = {
                      '_index': self.index_name,
                      '_source': doc
                  }
  
                  # Use specified field as document ID if present
                  if id_field and id_field in doc:
                      action['_id'] = doc[id_field]
  
                  actions.append(action)
  
              # Try to index batch with retries
              batch_success = False
              for attempt in range(self.max_retries):
                  try:
                      success, failed = bulk(
                          self.es_client.client,
                          actions,
                          raise_on_error=False,
                          raise_on_exception=False
                      )
  
                      success_count += success
                      if failed:
                          failed_count += len(failed)
                          errors.extend(failed)
  
                      batch_success = True
                      break
  
                  except BulkIndexError as e:
                      if attempt < self.max_retries - 1:
                          print(f"[BulkIndexer] Batch {batch_num} failed, retrying... "
                                f"(attempt {attempt + 1}/{self.max_retries})")
                          time.sleep(1)
                      else:
                          print(f"[BulkIndexer] Batch {batch_num} failed after "
                                f"{self.max_retries} attempts")
                          failed_count += len(batch)
                          errors.append({
                              'batch': batch_num,
                              'error': str(e)
                          })
  
                  except Exception as e:
                      print(f"[BulkIndexer] Unexpected error in batch {batch_num}: {e}")
                      failed_count += len(batch)
                      errors.append({
                          'batch': batch_num,
                          'error': str(e)
                      })
                      break
  
          elapsed_time = time.time() - start_time
  
          # Refresh index to make documents searchable
          self.es_client.refresh(self.index_name)
  
          results = {
              'total': total_docs,
              'success': success_count,
              'failed': failed_count,
              'elapsed_time': elapsed_time,
              'docs_per_second': total_docs / elapsed_time if elapsed_time > 0 else 0,
              'errors': errors[:10]  # Keep only first 10 errors
          }
  
          print(f"[BulkIndexer] Indexing complete!")
          print(f"  - Total: {total_docs}")
          print(f"  - Success: {success_count}")
          print(f"  - Failed: {failed_count}")
          print(f"  - Time: {elapsed_time:.2f}s")
          print(f"  - Speed: {results['docs_per_second']:.2f} docs/s")
  
          return results
  
      def delete_by_query(self, query: Dict[str, Any]) -> int:
          """
          Delete documents matching a query.
  
          Args:
              query: ES query DSL
  
          Returns:
              Number of documents deleted
          """
          try:
              response = self.es_client.client.delete_by_query(
                  index=self.index_name,
                  body={"query": query}
              )
              deleted = response.get('deleted', 0)
              print(f"[BulkIndexer] Deleted {deleted} documents")
              return deleted
          except Exception as e:
              print(f"[BulkIndexer] Delete by query failed: {e}")
              return 0
  
      def update_by_query(self, query: Dict[str, Any], script: Dict[str, Any]) -> int:
          """
          Update documents matching a query.
  
          Args:
              query: ES query DSL
              script: Update script
  
          Returns:
              Number of documents updated
          """
          try:
              response = self.es_client.client.update_by_query(
                  index=self.index_name,
                  body={
                      "query": query,
                      "script": script
                  }
              )
              updated = response.get('updated', 0)
              print(f"[BulkIndexer] Updated {updated} documents")
              return updated
          except Exception as e:
              print(f"[BulkIndexer] Update by query failed: {e}")
              return 0