Blame view

config/config_loader.py 25.1 KB
be52af70   tangwang   first commit
1
  """
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
2
  Configuration loader and validator for search engine configurations.
be52af70   tangwang   first commit
3
4
  
  This module handles loading, parsing, and validating YAML configuration files
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
5
  that define how search engine data should be indexed and searched.
be52af70   tangwang   first commit
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  """
  
  import yaml
  import os
  from typing import Dict, Any, List, Optional
  from dataclasses import dataclass, field
  from pathlib import Path
  
  from .field_types import (
      FieldConfig, FieldType, AnalyzerType,
      FIELD_TYPE_MAP, ANALYZER_MAP
  )
  
  
  @dataclass
  class IndexConfig:
      """Configuration for an index domain (e.g., default, title, brand)."""
      name: str
      label: str
      fields: List[str]  # List of field names to include
      analyzer: AnalyzerType
      boost: float = 1.0
      example: Optional[str] = None
  
b926f678   tangwang   多语言查询
30
31
32
      # Multi-language field mapping: {"zh": ["name"], "en": ["enSpuName"], "ru": ["ruSkuName"]}
      language_field_mapping: Optional[Dict[str, List[str]]] = None
  
be52af70   tangwang   first commit
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  
  @dataclass
  class RankingConfig:
      """Configuration for ranking expressions."""
      expression: str  # e.g., "bm25() + 0.2*text_embedding_relevance()"
      description: str
  
  
  @dataclass
  class QueryConfig:
      """Configuration for query processing."""
      supported_languages: List[str] = field(default_factory=lambda: ["zh", "en"])
      default_language: str = "zh"
      enable_translation: bool = True
      enable_text_embedding: bool = True
      enable_query_rewrite: bool = True
      rewrite_dictionary: Dict[str, str] = field(default_factory=dict)
  
      # Translation API settings
      translation_api_key: Optional[str] = None
      translation_service: str = "deepl"  # deepl, google, etc.
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
54
55
      translation_glossary_id: Optional[str] = None  # DeepL glossary ID for custom terminology
      translation_context: str = "e-commerce product search"  # Context hint for translation
be52af70   tangwang   first commit
56
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
57
      # Embedding field names - if not set, will auto-detect from fields
b73baf85   tangwang   撰写接口文档
58
      text_embedding_field: Optional[str] = None  # Field name for text embeddings (e.g., "title_embedding")
325eec03   tangwang   1. 日志、配置基础设施,使用优化
59
60
      image_embedding_field: Optional[str] = None  # Field name for image embeddings (e.g., "image_embedding")
  
9f96d6f3   tangwang   短query不用语义搜索
61
62
63
64
      # Embedding disable thresholds (disable vector search for short queries)
      embedding_disable_chinese_char_limit: int = 4  # Disable embedding for Chinese queries with <= this many characters
      embedding_disable_english_word_limit: int = 3  # Disable embedding for English queries with <= this many words
  
13377199   tangwang   接口优化
65
      # ES source fields configuration - fields to return in search results
cd3799c6   tangwang   tenant2 1w测试数据 mo...
66
67
68
      # If None, auto-collect from field configs (fields with return_in_source=True)
      # If empty list, return all fields. Otherwise, only return specified fields.
      source_fields: Optional[List[str]] = None
13377199   tangwang   接口优化
69
  
be52af70   tangwang   first commit
70
71
72
73
74
75
76
77
78
79
  
  @dataclass
  class SPUConfig:
      """Configuration for SPU aggregation."""
      enabled: bool = False
      spu_field: Optional[str] = None  # Field containing SPU ID
      inner_hits_size: int = 3
  
  
  @dataclass
a00c3672   tangwang   feat: Function Sc...
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  class FunctionScoreConfig:
      """Function Score配置(ES层打分规则)"""
      score_mode: str = "sum"  # multiply, sum, avg, first, max, min
      boost_mode: str = "multiply"  # multiply, replace, sum, avg, max, min
      functions: List[Dict[str, Any]] = field(default_factory=list)
  
  
  @dataclass
  class RerankConfig:
      """本地重排配置(当前禁用)"""
      enabled: bool = False
      expression: str = ""
      description: str = ""
  
  
  @dataclass
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
96
  class SearchConfig:
4d824a77   tangwang   所有租户共用一套统一配置.tena...
97
      """Complete configuration for search engine (multi-tenant)."""
be52af70   tangwang   first commit
98
99
100
101
102
103
104
105
106
107
108
109
      # Field definitions
      fields: List[FieldConfig]
  
      # Index structure (query domains)
      indexes: List[IndexConfig]
  
      # Query processing
      query_config: QueryConfig
  
      # Ranking configuration
      ranking: RankingConfig
  
a00c3672   tangwang   feat: Function Sc...
110
111
112
113
114
115
      # Function Score configuration (ES层打分)
      function_score: FunctionScoreConfig
  
      # Rerank configuration (本地重排)
      rerank: RerankConfig
  
be52af70   tangwang   first commit
116
117
118
119
120
      # SPU configuration
      spu_config: SPUConfig
  
      # ES index settings
      es_index_name: str
be52af70   tangwang   first commit
121
122
123
124
125
126
127
128
129
      es_settings: Dict[str, Any] = field(default_factory=dict)
  
  
  class ConfigurationError(Exception):
      """Raised when configuration validation fails."""
      pass
  
  
  class ConfigLoader:
4d824a77   tangwang   所有租户共用一套统一配置.tena...
130
      """Loads and validates unified search engine configuration from YAML file."""
be52af70   tangwang   first commit
131
  
4d824a77   tangwang   所有租户共用一套统一配置.tena...
132
133
      def __init__(self, config_file: str = "config/config.yaml"):
          self.config_file = Path(config_file)
a77693fe   tangwang   调整配置目录结构
134
      
4d824a77   tangwang   所有租户共用一套统一配置.tena...
135
      def _load_rewrite_dictionary(self) -> Dict[str, str]:
a77693fe   tangwang   调整配置目录结构
136
137
138
          """
          Load query rewrite dictionary from external file.
          
a77693fe   tangwang   调整配置目录结构
139
140
141
          Returns:
              Dictionary mapping query terms to rewritten queries
          """
4d824a77   tangwang   所有租户共用一套统一配置.tena...
142
143
          # Try config/query_rewrite.dict first
          dict_file = self.config_file.parent / "query_rewrite.dict"
a77693fe   tangwang   调整配置目录结构
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
          
          if not dict_file.exists():
              # Dictionary file is optional, return empty dict if not found
              return {}
          
          rewrite_dict = {}
          try:
              with open(dict_file, 'r', encoding='utf-8') as f:
                  for line_num, line in enumerate(f, 1):
                      line = line.strip()
                      # Skip empty lines and comments
                      if not line or line.startswith('#'):
                          continue
                      
                      # Parse tab-separated format
                      parts = line.split('\t')
                      if len(parts) != 2:
                          print(f"Warning: Invalid format in {dict_file} line {line_num}: {line}")
                          continue
                      
                      key, value = parts
                      rewrite_dict[key.strip()] = value.strip()
          except Exception as e:
              print(f"Error loading rewrite dictionary from {dict_file}: {e}")
              return {}
          
          return rewrite_dict
be52af70   tangwang   first commit
171
  
9f96d6f3   tangwang   短query不用语义搜索
172
      def load_config(self, validate: bool = True) -> SearchConfig:
be52af70   tangwang   first commit
173
          """
4d824a77   tangwang   所有租户共用一套统一配置.tena...
174
          Load unified configuration from YAML file.
be52af70   tangwang   first commit
175
  
9f96d6f3   tangwang   短query不用语义搜索
176
177
178
          Args:
              validate: Whether to validate configuration after loading (default: True)
  
be52af70   tangwang   first commit
179
          Returns:
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
180
              SearchConfig object
be52af70   tangwang   first commit
181
182
  
          Raises:
9f96d6f3   tangwang   短query不用语义搜索
183
              ConfigurationError: If config file not found, invalid, or validation fails
be52af70   tangwang   first commit
184
          """
4d824a77   tangwang   所有租户共用一套统一配置.tena...
185
186
          if not self.config_file.exists():
              raise ConfigurationError(f"Configuration file not found: {self.config_file}")
be52af70   tangwang   first commit
187
188
  
          try:
4d824a77   tangwang   所有租户共用一套统一配置.tena...
189
              with open(self.config_file, 'r', encoding='utf-8') as f:
be52af70   tangwang   first commit
190
191
                  config_data = yaml.safe_load(f)
          except yaml.YAMLError as e:
4d824a77   tangwang   所有租户共用一套统一配置.tena...
192
              raise ConfigurationError(f"Invalid YAML in {self.config_file}: {e}")
be52af70   tangwang   first commit
193
  
9f96d6f3   tangwang   短query不用语义搜索
194
195
196
197
198
199
200
201
202
203
          config = self._parse_config(config_data)
          
          # Auto-validate configuration
          if validate:
              errors = self.validate_config(config)
              if errors:
                  error_msg = "Configuration validation failed:\n" + "\n".join(f"  - {err}" for err in errors)
                  raise ConfigurationError(error_msg)
          
          return config
be52af70   tangwang   first commit
204
  
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
205
206
      def _parse_config(self, config_data: Dict[str, Any]) -> SearchConfig:
          """Parse configuration dictionary into SearchConfig object."""
be52af70   tangwang   first commit
207
208
209
210
211
212
213
214
215
216
217
218
219
  
          # Parse fields
          fields = []
          for field_data in config_data.get("fields", []):
              fields.append(self._parse_field_config(field_data))
  
          # Parse indexes
          indexes = []
          for index_data in config_data.get("indexes", []):
              indexes.append(self._parse_index_config(index_data))
  
          # Parse query config
          query_config_data = config_data.get("query_config", {})
a77693fe   tangwang   调整配置目录结构
220
221
          
          # Load rewrite dictionary from external file instead of config
4d824a77   tangwang   所有租户共用一套统一配置.tena...
222
          rewrite_dictionary = self._load_rewrite_dictionary()
a77693fe   tangwang   调整配置目录结构
223
          
cd3799c6   tangwang   tenant2 1w测试数据 mo...
224
225
226
227
228
229
230
231
232
          # Auto-collect source_fields from field configs if not explicitly specified
          source_fields = query_config_data.get("source_fields")
          if source_fields is None:
              # Auto-collect fields with return_in_source=True
              source_fields = [
                  field.name for field in fields 
                  if field.return_in_source
              ]
          
9f96d6f3   tangwang   短query不用语义搜索
233
234
235
          # Parse embedding disable thresholds
          embedding_thresholds = query_config_data.get("embedding_disable_thresholds", {})
          
be52af70   tangwang   first commit
236
          query_config = QueryConfig(
9f96d6f3   tangwang   短query不用语义搜索
237
238
              supported_languages=query_config_data.get("supported_languages") or ["zh", "en"],
              default_language=query_config_data.get("default_language") or "zh",
be52af70   tangwang   first commit
239
240
241
              enable_translation=query_config_data.get("enable_translation", True),
              enable_text_embedding=query_config_data.get("enable_text_embedding", True),
              enable_query_rewrite=query_config_data.get("enable_query_rewrite", True),
a77693fe   tangwang   调整配置目录结构
242
              rewrite_dictionary=rewrite_dictionary,
be52af70   tangwang   first commit
243
              translation_api_key=query_config_data.get("translation_api_key"),
9f96d6f3   tangwang   短query不用语义搜索
244
              translation_service=query_config_data.get("translation_service") or "deepl",
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
245
              translation_glossary_id=query_config_data.get("translation_glossary_id"),
9f96d6f3   tangwang   短query不用语义搜索
246
              translation_context=query_config_data.get("translation_context") or "e-commerce product search",
325eec03   tangwang   1. 日志、配置基础设施,使用优化
247
              text_embedding_field=query_config_data.get("text_embedding_field"),
cd3799c6   tangwang   tenant2 1w测试数据 mo...
248
              image_embedding_field=query_config_data.get("image_embedding_field"),
9f96d6f3   tangwang   短query不用语义搜索
249
250
              embedding_disable_chinese_char_limit=embedding_thresholds.get("chinese_char_limit", 4),
              embedding_disable_english_word_limit=embedding_thresholds.get("english_word_limit", 3),
cd3799c6   tangwang   tenant2 1w测试数据 mo...
251
              source_fields=source_fields
be52af70   tangwang   first commit
252
253
254
255
256
          )
  
          # Parse ranking config
          ranking_data = config_data.get("ranking", {})
          ranking = RankingConfig(
9f96d6f3   tangwang   短query不用语义搜索
257
258
              expression=ranking_data.get("expression") or "bm25() + 0.2*text_embedding_relevance()",
              description=ranking_data.get("description") or "Default BM25 + text embedding ranking"
be52af70   tangwang   first commit
259
260
          )
  
a00c3672   tangwang   feat: Function Sc...
261
262
263
          # Parse Function Score configuration
          fs_data = config_data.get("function_score", {})
          function_score = FunctionScoreConfig(
9f96d6f3   tangwang   短query不用语义搜索
264
265
266
              score_mode=fs_data.get("score_mode") or "sum",
              boost_mode=fs_data.get("boost_mode") or "multiply",
              functions=fs_data.get("functions") or []
a00c3672   tangwang   feat: Function Sc...
267
268
269
270
271
272
          )
  
          # Parse Rerank configuration
          rerank_data = config_data.get("rerank", {})
          rerank = RerankConfig(
              enabled=rerank_data.get("enabled", False),
9f96d6f3   tangwang   短query不用语义搜索
273
274
              expression=rerank_data.get("expression") or "",
              description=rerank_data.get("description") or ""
a00c3672   tangwang   feat: Function Sc...
275
276
          )
  
be52af70   tangwang   first commit
277
278
279
280
281
282
283
284
          # Parse SPU config
          spu_data = config_data.get("spu_config", {})
          spu_config = SPUConfig(
              enabled=spu_data.get("enabled", False),
              spu_field=spu_data.get("spu_field"),
              inner_hits_size=spu_data.get("inner_hits_size", 3)
          )
  
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
285
          return SearchConfig(
be52af70   tangwang   first commit
286
287
288
289
              fields=fields,
              indexes=indexes,
              query_config=query_config,
              ranking=ranking,
a00c3672   tangwang   feat: Function Sc...
290
291
              function_score=function_score,
              rerank=rerank,
be52af70   tangwang   first commit
292
              spu_config=spu_config,
4d824a77   tangwang   所有租户共用一套统一配置.tena...
293
              es_index_name=config_data.get("es_index_name", "search_products"),
be52af70   tangwang   first commit
294
295
296
297
298
299
300
              es_settings=config_data.get("es_settings", {})
          )
  
      def _parse_field_config(self, field_data: Dict[str, Any]) -> FieldConfig:
          """Parse field configuration from dictionary."""
          name = field_data["name"]
          field_type_str = field_data["type"]
cadc77b6   tangwang   索引字段名、变量名、API数据结构...
301
          field_type_raw = field_type_str
be52af70   tangwang   first commit
302
303
304
305
306
  
          # Map field type string to enum
          if field_type_str not in FIELD_TYPE_MAP:
              raise ConfigurationError(f"Unknown field type: {field_type_str}")
          field_type = FIELD_TYPE_MAP[field_type_str]
cadc77b6   tangwang   索引字段名、变量名、API数据结构...
307
          is_hktext = field_type_str.lower() == "hktext"
be52af70   tangwang   first commit
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
  
          # Map analyzer string to enum (if provided)
          analyzer = None
          analyzer_str = field_data.get("analyzer")
          if analyzer_str and analyzer_str in ANALYZER_MAP:
              analyzer = ANALYZER_MAP[analyzer_str]
  
          search_analyzer = None
          search_analyzer_str = field_data.get("search_analyzer")
          if search_analyzer_str and search_analyzer_str in ANALYZER_MAP:
              search_analyzer = ANALYZER_MAP[search_analyzer_str]
  
          return FieldConfig(
              name=name,
              field_type=field_type,
be52af70   tangwang   first commit
323
324
325
326
327
              analyzer=analyzer,
              search_analyzer=search_analyzer,
              required=field_data.get("required", False),
              multi_language=field_data.get("multi_language", False),
              languages=field_data.get("languages"),
cd3799c6   tangwang   tenant2 1w测试数据 mo...
328
              return_in_source=field_data.get("return_in_source", True),  # Default to True
be52af70   tangwang   first commit
329
330
331
332
333
334
              boost=field_data.get("boost", 1.0),
              store=field_data.get("store", False),
              index=field_data.get("index", True),
              embedding_dims=field_data.get("embedding_dims", 1024),
              embedding_similarity=field_data.get("embedding_similarity", "dot_product"),
              nested=field_data.get("nested", False),
cadc77b6   tangwang   索引字段名、变量名、API数据结构...
335
336
              nested_properties=field_data.get("nested_properties"),
              keyword_subfield=field_data.get("keyword_subfield", is_hktext),
5dcddc06   tangwang   索引重构
337
338
              keyword_ignore_above=field_data.get("keyword_ignore_above", 256),
              keyword_normalizer=field_data.get("keyword_normalizer")
be52af70   tangwang   first commit
339
340
341
342
343
344
345
346
          )
  
      def _parse_index_config(self, index_data: Dict[str, Any]) -> IndexConfig:
          """Parse index configuration from dictionary."""
          analyzer_str = index_data.get("analyzer", "chinese_ecommerce")
          if analyzer_str not in ANALYZER_MAP:
              raise ConfigurationError(f"Unknown analyzer: {analyzer_str}")
  
b926f678   tangwang   多语言查询
347
348
349
          # Parse language field mapping if present
          language_field_mapping = index_data.get("language_field_mapping")
  
be52af70   tangwang   first commit
350
351
352
353
354
355
          return IndexConfig(
              name=index_data["name"],
              label=index_data.get("label", index_data["name"]),
              fields=index_data["fields"],
              analyzer=ANALYZER_MAP[analyzer_str],
              boost=index_data.get("boost", 1.0),
b926f678   tangwang   多语言查询
356
357
              example=index_data.get("example"),
              language_field_mapping=language_field_mapping
be52af70   tangwang   first commit
358
359
          )
  
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
360
      def validate_config(self, config: SearchConfig) -> List[str]:
be52af70   tangwang   first commit
361
          """
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
362
          Validate search configuration.
be52af70   tangwang   first commit
363
364
  
          Args:
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
365
              config: Search configuration to validate
be52af70   tangwang   first commit
366
367
368
369
370
371
372
373
  
          Returns:
              List of validation error messages (empty if valid)
          """
          errors = []
  
          # Validate field references in indexes
          field_names = {field.name for field in config.fields}
b926f678   tangwang   多语言查询
374
375
          field_map = {field.name: field for field in config.fields}
          
be52af70   tangwang   first commit
376
          for index in config.indexes:
b926f678   tangwang   多语言查询
377
              # Validate fields in index.fields
be52af70   tangwang   first commit
378
379
380
              for field_name in index.fields:
                  if field_name not in field_names:
                      errors.append(f"Index '{index.name}' references unknown field '{field_name}'")
b926f678   tangwang   多语言查询
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
              
              # Validate language_field_mapping if present
              if index.language_field_mapping:
                  for lang, field_list in index.language_field_mapping.items():
                      if not isinstance(field_list, list):
                          errors.append(f"Index '{index.name}': language_field_mapping['{lang}'] must be a list")
                          continue
                      
                      for field_name in field_list:
                          # Check if field exists
                          if field_name not in field_names:
                              errors.append(
                                  f"Index '{index.name}': language_field_mapping['{lang}'] "
                                  f"references unknown field '{field_name}'"
                              )
                          else:
                              # Check if field is TEXT type (multi-language fields should be text fields)
                              field = field_map[field_name]
                              if field.field_type != FieldType.TEXT:
                                  errors.append(
                                      f"Index '{index.name}': language_field_mapping['{lang}'] "
                                      f"field '{field_name}' must be of type TEXT, got {field.field_type.value}"
                                  )
                              
                              # Verify analyzer is appropriate for the language
                              # This is a soft check - we just warn if analyzer doesn't match language
                              if field.analyzer:
                                  analyzer_name = field.analyzer.value.lower()
                                  expected_analyzers = {
                                      'zh': ['chinese', 'index_ansj', 'query_ansj'],
                                      'en': ['english'],
                                      'ru': ['russian'],
                                      'ar': ['arabic'],
                                      'es': ['spanish'],
                                      'ja': ['japanese']
                                  }
                                  if lang in expected_analyzers:
                                      expected = expected_analyzers[lang]
                                      if not any(exp in analyzer_name for exp in expected):
                                          # Warning only, not an error
                                          print(
                                              f"Warning: Index '{index.name}': field '{field_name}' for language '{lang}' "
                                              f"uses analyzer '{analyzer_name}', which may not be optimal for '{lang}'"
                                          )
be52af70   tangwang   first commit
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
  
          # Validate SPU config
          if config.spu_config.enabled:
              if not config.spu_config.spu_field:
                  errors.append("SPU aggregation enabled but no spu_field specified")
              elif config.spu_config.spu_field not in field_names:
                  errors.append(f"SPU field '{config.spu_config.spu_field}' not found in fields")
  
          # Validate embedding fields have proper configuration
          for field in config.fields:
              if field.field_type in [FieldType.TEXT_EMBEDDING, FieldType.IMAGE_EMBEDDING]:
                  if field.embedding_dims <= 0:
                      errors.append(f"Field '{field.name}': embedding_dims must be positive")
                  if field.embedding_similarity not in ["dot_product", "cosine", "l2_norm"]:
                      errors.append(f"Field '{field.name}': invalid embedding_similarity")
  
1f6d15fa   tangwang   重构:SPU级别索引、统一索引架构...
441
442
443
444
445
446
447
448
449
450
451
          # Validate tenant_id field (required)
          tenant_id_field = None
          for field in config.fields:
              if field.name == "tenant_id":
                  tenant_id_field = field
                  break
          
          if not tenant_id_field:
              errors.append("Required field 'tenant_id' not found in fields")
          elif not tenant_id_field.required:
              errors.append("Field 'tenant_id' must be marked as required")
be52af70   tangwang   first commit
452
453
454
  
          return errors
  
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
455
      def save_config(self, config: SearchConfig, output_path: Optional[str] = None) -> None:
be52af70   tangwang   first commit
456
          """
4d824a77   tangwang   所有租户共用一套统一配置.tena...
457
          Save configuration to YAML file.
a77693fe   tangwang   调整配置目录结构
458
459
          
          Note: rewrite_dictionary is saved separately to query_rewrite.dict file
be52af70   tangwang   first commit
460
461
462
  
          Args:
              config: Configuration to save
4d824a77   tangwang   所有租户共用一套统一配置.tena...
463
              output_path: Optional output path (defaults to config/config.yaml)
be52af70   tangwang   first commit
464
465
          """
          if output_path is None:
4d824a77   tangwang   所有租户共用一套统一配置.tena...
466
467
468
              output_path = self.config_file
          else:
              output_path = Path(output_path)
be52af70   tangwang   first commit
469
470
  
          # Convert config back to dictionary format
9f96d6f3   tangwang   短query不用语义搜索
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
          query_config_dict = {
              "supported_languages": config.query_config.supported_languages,
              "default_language": config.query_config.default_language,
              "enable_translation": config.query_config.enable_translation,
              "enable_text_embedding": config.query_config.enable_text_embedding,
              "enable_query_rewrite": config.query_config.enable_query_rewrite,
              "translation_service": config.query_config.translation_service,
          }
          
          # Add optional fields only if they are set
          if config.query_config.translation_api_key:
              query_config_dict["translation_api_key"] = config.query_config.translation_api_key
          if config.query_config.translation_glossary_id:
              query_config_dict["translation_glossary_id"] = config.query_config.translation_glossary_id
          if config.query_config.translation_context:
              query_config_dict["translation_context"] = config.query_config.translation_context
          if config.query_config.text_embedding_field:
              query_config_dict["text_embedding_field"] = config.query_config.text_embedding_field
          if config.query_config.image_embedding_field:
              query_config_dict["image_embedding_field"] = config.query_config.image_embedding_field
          if config.query_config.source_fields:
              query_config_dict["source_fields"] = config.query_config.source_fields
          
          # Add embedding disable thresholds
          if (config.query_config.embedding_disable_chinese_char_limit != 4 or 
              config.query_config.embedding_disable_english_word_limit != 3):
              query_config_dict["embedding_disable_thresholds"] = {
                  "chinese_char_limit": config.query_config.embedding_disable_chinese_char_limit,
                  "english_word_limit": config.query_config.embedding_disable_english_word_limit
              }
          
be52af70   tangwang   first commit
502
          config_dict = {
be52af70   tangwang   first commit
503
504
505
506
              "es_index_name": config.es_index_name,
              "es_settings": config.es_settings,
              "fields": [self._field_to_dict(field) for field in config.fields],
              "indexes": [self._index_to_dict(index) for index in config.indexes],
9f96d6f3   tangwang   短query不用语义搜索
507
              "query_config": query_config_dict,
be52af70   tangwang   first commit
508
509
510
511
              "ranking": {
                  "expression": config.ranking.expression,
                  "description": config.ranking.description
              },
1f6d15fa   tangwang   重构:SPU级别索引、统一索引架构...
512
513
514
515
516
517
518
519
520
521
              "function_score": {
                  "score_mode": config.function_score.score_mode,
                  "boost_mode": config.function_score.boost_mode,
                  "functions": config.function_score.functions
              },
              "rerank": {
                  "enabled": config.rerank.enabled,
                  "expression": config.rerank.expression,
                  "description": config.rerank.description
              },
be52af70   tangwang   first commit
522
523
524
525
526
527
528
              "spu_config": {
                  "enabled": config.spu_config.enabled,
                  "spu_field": config.spu_config.spu_field,
                  "inner_hits_size": config.spu_config.inner_hits_size
              }
          }
  
4d824a77   tangwang   所有租户共用一套统一配置.tena...
529
          output_path.parent.mkdir(parents=True, exist_ok=True)
be52af70   tangwang   first commit
530
531
          with open(output_path, 'w', encoding='utf-8') as f:
              yaml.dump(config_dict, f, default_flow_style=False, allow_unicode=True)
a77693fe   tangwang   调整配置目录结构
532
533
          
          # Save rewrite dictionary to separate file
4d824a77   tangwang   所有租户共用一套统一配置.tena...
534
          self._save_rewrite_dictionary(config.query_config.rewrite_dictionary)
a77693fe   tangwang   调整配置目录结构
535
      
4d824a77   tangwang   所有租户共用一套统一配置.tena...
536
      def _save_rewrite_dictionary(self, rewrite_dict: Dict[str, str]) -> None:
a77693fe   tangwang   调整配置目录结构
537
538
539
540
          """
          Save rewrite dictionary to external file.
          
          Args:
a77693fe   tangwang   调整配置目录结构
541
542
              rewrite_dict: Dictionary to save
          """
4d824a77   tangwang   所有租户共用一套统一配置.tena...
543
544
          dict_file = self.config_file.parent / "query_rewrite.dict"
          dict_file.parent.mkdir(parents=True, exist_ok=True)
a77693fe   tangwang   调整配置目录结构
545
546
547
548
          
          with open(dict_file, 'w', encoding='utf-8') as f:
              for key, value in rewrite_dict.items():
                  f.write(f"{key}\t{value}\n")
be52af70   tangwang   first commit
549
550
  
      def _field_to_dict(self, field: FieldConfig) -> Dict[str, Any]:
9f96d6f3   tangwang   短query不用语义搜索
551
          """Convert FieldConfig to dictionary, preserving all fields."""
be52af70   tangwang   first commit
552
553
554
          result = {
              "name": field.name,
              "type": field.field_type.value,
be52af70   tangwang   first commit
555
556
557
558
              "required": field.required,
              "boost": field.boost,
              "store": field.store,
              "index": field.index,
9f96d6f3   tangwang   短query不用语义搜索
559
              "return_in_source": field.return_in_source,
be52af70   tangwang   first commit
560
561
          }
  
9f96d6f3   tangwang   短query不用语义搜索
562
          # Add optional fields only if they differ from defaults or are set
be52af70   tangwang   first commit
563
564
565
566
567
568
          if field.analyzer:
              result["analyzer"] = field.analyzer.value
          if field.search_analyzer:
              result["search_analyzer"] = field.search_analyzer.value
          if field.multi_language:
              result["multi_language"] = field.multi_language
9f96d6f3   tangwang   短query不用语义搜索
569
570
              if field.languages:
                  result["languages"] = field.languages
be52af70   tangwang   first commit
571
572
573
574
575
576
          if field.embedding_dims != 1024:
              result["embedding_dims"] = field.embedding_dims
          if field.embedding_similarity != "dot_product":
              result["embedding_similarity"] = field.embedding_similarity
          if field.nested:
              result["nested"] = field.nested
9f96d6f3   tangwang   短query不用语义搜索
577
578
579
580
581
582
583
584
              if field.nested_properties:
                  result["nested_properties"] = field.nested_properties
          if field.keyword_subfield:
              result["keyword_subfield"] = field.keyword_subfield
              if field.keyword_ignore_above != 256:
                  result["keyword_ignore_above"] = field.keyword_ignore_above
              if field.keyword_normalizer:
                  result["keyword_normalizer"] = field.keyword_normalizer
be52af70   tangwang   first commit
585
586
587
588
  
          return result
  
      def _index_to_dict(self, index: IndexConfig) -> Dict[str, Any]:
9f96d6f3   tangwang   短query不用语义搜索
589
          """Convert IndexConfig to dictionary, preserving all fields."""
b926f678   tangwang   多语言查询
590
          result = {
be52af70   tangwang   first commit
591
592
593
594
              "name": index.name,
              "label": index.label,
              "fields": index.fields,
              "analyzer": index.analyzer.value,
b926f678   tangwang   多语言查询
595
          }
9f96d6f3   tangwang   短query不用语义搜索
596
597
598
599
600
601
          
          # Add optional fields only if they differ from defaults or are set
          if index.boost != 1.0:
              result["boost"] = index.boost
          if index.example:
              result["example"] = index.example
b926f678   tangwang   多语言查询
602
603
604
605
          if index.language_field_mapping:
              result["language_field_mapping"] = index.language_field_mapping
  
          return result