Blame view

utils/es_client.py 10.5 KB
be52af70   tangwang   first commit
1
2
3
4
5
  """
  Elasticsearch client wrapper.
  """
  
  from elasticsearch import Elasticsearch
325eec03   tangwang   1. 日志、配置基础设施,使用优化
6
  from elasticsearch.helpers import bulk
be52af70   tangwang   first commit
7
  from typing import Dict, Any, List, Optional
325eec03   tangwang   1. 日志、配置基础设施,使用优化
8
9
  import logging
  
86d8358b   tangwang   config optimize
10
  from config.loader import get_app_config
325eec03   tangwang   1. 日志、配置基础设施,使用优化
11
12
  
  logger = logging.getLogger(__name__)
be52af70   tangwang   first commit
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  
  
  class ESClient:
      """Wrapper for Elasticsearch client with common operations."""
  
      def __init__(
          self,
          hosts: List[str] = None,
          username: Optional[str] = None,
          password: Optional[str] = None,
          **kwargs
      ):
          """
          Initialize Elasticsearch client.
  
          Args:
              hosts: List of ES host URLs (default: ['http://localhost:9200'])
              username: ES username (optional)
              password: ES password (optional)
              **kwargs: Additional ES client parameters
          """
          if hosts is None:
86d8358b   tangwang   config optimize
35
              hosts = [get_app_config().infrastructure.elasticsearch.host]
be52af70   tangwang   first commit
36
37
38
39
40
41
42
43
44
45
46
  
          # Build client config
          client_config = {
              'hosts': hosts,
              'timeout': 30,
              'max_retries': 3,
              'retry_on_timeout': True,
          }
  
          # Add authentication if provided
          if username and password:
ff9efda0   tangwang   suggest
47
              client_config['basic_auth'] = (username, password)
be52af70   tangwang   first commit
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  
          # Merge additional kwargs
          client_config.update(kwargs)
  
          self.client = Elasticsearch(**client_config)
  
      def ping(self) -> bool:
          """
          Test connection to Elasticsearch.
  
          Returns:
              True if connected, False otherwise
          """
          try:
              return self.client.ping()
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
64
              logger.error(f"Failed to ping Elasticsearch: {e}", exc_info=True)
be52af70   tangwang   first commit
65
66
67
68
69
70
71
72
73
74
75
              return False
  
      def create_index(self, index_name: str, body: Dict[str, Any]) -> bool:
          """
          Create an index.
  
          Args:
              index_name: Name of the index
              body: Index configuration (settings + mappings)
  
          Returns:
41e1f8df   tangwang   店匠体系数据的搜索:mock da...
76
              True if successful, False otherwise
be52af70   tangwang   first commit
77
78
79
          """
          try:
              self.client.indices.create(index=index_name, body=body)
325eec03   tangwang   1. 日志、配置基础设施,使用优化
80
              logger.info(f"Index '{index_name}' created successfully")
be52af70   tangwang   first commit
81
82
              return True
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
83
              logger.error(f"Failed to create index '{index_name}': {e}", exc_info=True)
be52af70   tangwang   first commit
84
85
              return False
  
ff9efda0   tangwang   suggest
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
      def put_alias(self, index_name: str, alias_name: str) -> bool:
          """Add alias for an index."""
          try:
              self.client.indices.put_alias(index=index_name, name=alias_name)
              return True
          except Exception as e:
              logger.error(
                  "Failed to put alias '%s' for index '%s': %s",
                  alias_name,
                  index_name,
                  e,
                  exc_info=True,
              )
              return False
  
      def alias_exists(self, alias_name: str) -> bool:
          """Check if alias exists."""
          try:
              return self.client.indices.exists_alias(name=alias_name)
          except Exception as e:
              logger.error("Failed to check alias exists '%s': %s", alias_name, e, exc_info=True)
              return False
  
      def get_alias_indices(self, alias_name: str) -> List[str]:
          """Get concrete indices behind alias."""
          try:
              result = self.client.indices.get_alias(name=alias_name)
              return sorted(list((result or {}).keys()))
          except Exception:
              return []
  
      def update_aliases(self, actions: List[Dict[str, Any]]) -> bool:
          """Atomically update aliases."""
          try:
              self.client.indices.update_aliases(body={"actions": actions})
              return True
          except Exception as e:
              logger.error("Failed to update aliases: %s", e, exc_info=True)
              return False
  
      def list_indices(self, pattern: str) -> List[str]:
          """List indices by wildcard pattern."""
          try:
              result = self.client.indices.get(index=pattern, allow_no_indices=True)
              return sorted(list((result or {}).keys()))
          except Exception:
              return []
  
be52af70   tangwang   first commit
134
135
136
137
138
139
140
141
142
143
144
145
146
      def delete_index(self, index_name: str) -> bool:
          """
          Delete an index.
  
          Args:
              index_name: Name of the index
  
          Returns:
              True if successful
          """
          try:
              if self.client.indices.exists(index=index_name):
                  self.client.indices.delete(index=index_name)
325eec03   tangwang   1. 日志、配置基础设施,使用优化
147
                  logger.info(f"Index '{index_name}' deleted successfully")
be52af70   tangwang   first commit
148
149
                  return True
              else:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
150
                  logger.warning(f"Index '{index_name}' does not exist")
be52af70   tangwang   first commit
151
152
                  return False
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
153
              logger.error(f"Failed to delete index '{index_name}': {e}", exc_info=True)
be52af70   tangwang   first commit
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
              return False
  
      def index_exists(self, index_name: str) -> bool:
          """Check if index exists."""
          return self.client.indices.exists(index=index_name)
  
      def bulk_index(self, index_name: str, docs: List[Dict[str, Any]]) -> Dict[str, Any]:
          """
          Bulk index documents.
  
          Args:
              index_name: Name of the index
              docs: List of documents to index
  
          Returns:
              Dictionary with results
          """
be52af70   tangwang   first commit
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
          actions = []
          for doc in docs:
              action = {
                  '_index': index_name,
                  '_source': doc
              }
              # If document has _id field, use it
              if '_id' in doc:
                  action['_id'] = doc['_id']
                  del doc['_id']
  
              actions.append(action)
  
          try:
              success, failed = bulk(self.client, actions, raise_on_error=False)
              return {
                  'success': success,
                  'failed': len(failed),
                  'errors': failed
              }
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
192
              logger.error(f"Bulk indexing failed: {e}", exc_info=True)
be52af70   tangwang   first commit
193
194
195
196
197
198
              return {
                  'success': 0,
                  'failed': len(docs),
                  'errors': [str(e)]
              }
  
ff9efda0   tangwang   suggest
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
      def bulk_actions(self, actions: List[Dict[str, Any]]) -> Dict[str, Any]:
          """
          Execute generic bulk actions.
  
          Args:
              actions: elasticsearch.helpers.bulk compatible action list
          """
          if not actions:
              return {'success': 0, 'failed': 0, 'errors': []}
          try:
              success, failed = bulk(self.client, actions, raise_on_error=False)
              return {
                  'success': success,
                  'failed': len(failed),
                  'errors': failed
              }
          except Exception as e:
              logger.error("Bulk actions failed: %s", e, exc_info=True)
              return {
                  'success': 0,
                  'failed': len(actions),
                  'errors': [str(e)],
              }
  
be52af70   tangwang   first commit
223
224
225
226
227
      def search(
          self,
          index_name: str,
          body: Dict[str, Any],
          size: int = 10,
ff9efda0   tangwang   suggest
228
229
          from_: int = 0,
          routing: Optional[str] = None,
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
230
          include_named_queries_score: bool = False,
be52af70   tangwang   first commit
231
232
233
234
235
236
237
238
239
240
241
242
243
      ) -> Dict[str, Any]:
          """
          Execute search query.
  
          Args:
              index_name: Name of the index
              body: Search query body
              size: Number of results to return
              from_: Offset for pagination
  
          Returns:
              Search results
          """
bf89b597   tangwang   feat(search): ada...
244
245
246
247
248
249
250
251
252
253
254
255
          # Safety guard: collapse is no longer needed (index is already SPU-level).
          # If any caller accidentally adds a collapse clause (e.g. on product_id),
          # strip it here to avoid 400 errors like:
          # "no mapping found for `product_id` in order to collapse on"
          if isinstance(body, dict) and "collapse" in body:
              logger.warning(
                  "Removing unsupported 'collapse' clause from ES query body: %s",
                  body.get("collapse")
              )
              body = dict(body)  # shallow copy to avoid mutating caller
              body.pop("collapse", None)
  
be52af70   tangwang   first commit
256
          try:
5f7d7f09   tangwang   性能测试报告.md
257
              response = self.client.search(
be52af70   tangwang   first commit
258
259
260
                  index=index_name,
                  body=body,
                  size=size,
ff9efda0   tangwang   suggest
261
262
                  from_=from_,
                  routing=routing,
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
263
                  include_named_queries_score=include_named_queries_score,
be52af70   tangwang   first commit
264
              )
5f7d7f09   tangwang   性能测试报告.md
265
266
267
268
269
270
271
272
273
274
              # elasticsearch-py 8.x returns ObjectApiResponse; normalize to mutable dict
              # so caller can safely patch hits/took during post-processing.
              if hasattr(response, "body"):
                  payload = response.body
                  if isinstance(payload, dict):
                      return dict(payload)
                  return payload
              if isinstance(response, dict):
                  return response
              return dict(response)
be52af70   tangwang   first commit
275
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
276
              logger.error(f"Search failed: {e}", exc_info=True)
26b910bd   tangwang   refactor service ...
277
              raise RuntimeError(f"Elasticsearch search failed for index '{index_name}': {e}") from e
be52af70   tangwang   first commit
278
279
280
281
282
283
  
      def get_mapping(self, index_name: str) -> Dict[str, Any]:
          """Get index mapping."""
          try:
              return self.client.indices.get_mapping(index=index_name)
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
284
              logger.error(f"Failed to get mapping for '{index_name}': {e}", exc_info=True)
be52af70   tangwang   first commit
285
286
287
288
289
290
291
292
              return {}
  
      def refresh(self, index_name: str) -> bool:
          """Refresh index to make documents searchable."""
          try:
              self.client.indices.refresh(index=index_name)
              return True
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
293
              logger.error(f"Failed to refresh index '{index_name}': {e}", exc_info=True)
be52af70   tangwang   first commit
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
              return False
  
      def count(self, index_name: str, body: Optional[Dict[str, Any]] = None) -> int:
          """
          Count documents in index.
  
          Args:
              index_name: Name of the index
              body: Optional query body
  
          Returns:
              Document count
          """
          try:
              result = self.client.count(index=index_name, body=body)
              return result['count']
          except Exception as e:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
311
              logger.error(f"Count failed: {e}", exc_info=True)
26b910bd   tangwang   refactor service ...
312
              raise RuntimeError(f"Elasticsearch count failed for index '{index_name}': {e}") from e
be52af70   tangwang   first commit
313
314
315
316
317
318
319
320
321
322
323
324
325
326
  
  
  def get_es_client_from_env() -> ESClient:
      """
      Create ES client from environment variables.
  
      Environment variables:
          ES_HOST: Elasticsearch host URL (default: http://localhost:9200)
          ES_USERNAME: Username (optional)
          ES_PASSWORD: Password (optional)
  
      Returns:
          ESClient instance
      """
86d8358b   tangwang   config optimize
327
328
329
330
331
332
      cfg = get_app_config().infrastructure.elasticsearch
      return ESClient(
          hosts=[cfg.host],
          username=cfg.username,
          password=cfg.password,
      )