Blame view

indexer/mapping_generator.py 6.26 KB
be52af70   tangwang   first commit
1
2
3
  """
  Elasticsearch mapping generator.
  
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
4
  Generates Elasticsearch index mappings from search configuration.
be52af70   tangwang   first commit
5
6
7
8
  """
  
  from typing import Dict, Any
  from config import (
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
9
      SearchConfig,
be52af70   tangwang   first commit
10
11
12
13
14
15
16
17
      FieldConfig,
      get_es_mapping_for_field,
      get_default_analyzers,
      get_default_similarity
  )
  
  
  class MappingGenerator:
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
18
      """Generates Elasticsearch mapping from search configuration."""
be52af70   tangwang   first commit
19
  
9cb7528e   tangwang   店匠体系数据的搜索:mock da...
20
      def __init__(self, config: SearchConfig):
be52af70   tangwang   first commit
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
          self.config = config
  
      def generate_mapping(self) -> Dict[str, Any]:
          """
          Generate complete Elasticsearch index configuration including
          settings and mappings.
  
          Returns:
              Dictionary containing index configuration
          """
          return {
              "settings": self._generate_settings(),
              "mappings": self._generate_mappings()
          }
  
      def _generate_settings(self) -> Dict[str, Any]:
          """Generate index settings."""
          settings = {
              "number_of_shards": self.config.es_settings.get("number_of_shards", 1),
              "number_of_replicas": self.config.es_settings.get("number_of_replicas", 0),
              "refresh_interval": self.config.es_settings.get("refresh_interval", "30s"),
          }
  
          # Add similarity configuration (modified BM25)
          similarity_config = get_default_similarity()
          settings.update(similarity_config)
  
          # Add analyzer configuration
          analyzer_config = get_default_analyzers()
          settings.update(analyzer_config)
  
          # Merge any custom settings from config
          for key, value in self.config.es_settings.items():
              if key not in ["number_of_shards", "number_of_replicas", "refresh_interval"]:
                  settings[key] = value
  
          return settings
  
      def _generate_mappings(self) -> Dict[str, Any]:
          """Generate field mappings."""
          properties = {}
  
          for field in self.config.fields:
              field_mapping = get_es_mapping_for_field(field)
              properties[field.name] = field_mapping
  
          return {
              "properties": properties
          }
  
      def get_default_domain_fields(self) -> list:
          """
          Get list of fields in the 'default' domain.
  
          Returns:
              List of field names
          """
          for index in self.config.indexes:
              if index.name == "default":
                  return index.fields
          return []
  
      def get_text_embedding_field(self) -> str:
          """
          Get the primary text embedding field name.
  
          Returns:
              Field name or empty string if not found
          """
          # Look for name_embedding or first text_embedding field
          for field in self.config.fields:
              if field.name == "name_embedding":
                  return field.name
  
          # Otherwise return first text embedding field
          for field in self.config.fields:
              if "embedding" in field.name and "image" not in field.name:
                  return field.name
  
          return ""
  
      def get_image_embedding_field(self) -> str:
          """
          Get the primary image embedding field name.
  
          Returns:
              Field name or empty string if not found
          """
          for field in self.config.fields:
              if "image" in field.name and "embedding" in field.name:
                  return field.name
          return ""
  
      def get_field_by_name(self, field_name: str) -> FieldConfig:
          """
          Get field configuration by name.
  
          Args:
              field_name: Field name
  
          Returns:
              FieldConfig object or None if not found
          """
          for field in self.config.fields:
              if field.name == field_name:
                  return field
          return None
  
      def get_match_fields_for_domain(self, domain_name: str = "default") -> list:
          """
          Get list of text fields for matching in a domain.
  
          Args:
              domain_name: Name of the query domain
  
          Returns:
              List of field names with optional boost (e.g., ["name^2.0", "category^1.5"])
          """
          for index in self.config.indexes:
              if index.name == domain_name:
                  result = []
                  for field_name in index.fields:
                      field = self.get_field_by_name(field_name)
                      if field and field.boost != 1.0:
                          result.append(f"{field_name}^{field.boost}")
                      else:
                          result.append(field_name)
                  return result
          return []
  
  
  def create_index_if_not_exists(es_client, index_name: str, mapping: Dict[str, Any]) -> bool:
      """
      Create Elasticsearch index if it doesn't exist.
  
      Args:
          es_client: Elasticsearch client instance
          index_name: Name of the index to create
          mapping: Index mapping configuration
  
      Returns:
          True if index was created, False if it already exists
      """
      if es_client.indices.exists(index=index_name):
          print(f"Index '{index_name}' already exists")
          return False
  
      es_client.indices.create(index=index_name, body=mapping)
      print(f"Index '{index_name}' created successfully")
      return True
  
  
  def delete_index_if_exists(es_client, index_name: str) -> bool:
      """
      Delete Elasticsearch index if it exists.
  
      Args:
          es_client: Elasticsearch client instance
          index_name: Name of the index to delete
  
      Returns:
          True if index was deleted, False if it didn't exist
      """
      if not es_client.indices.exists(index=index_name):
          print(f"Index '{index_name}' does not exist")
          return False
  
      es_client.indices.delete(index=index_name)
      print(f"Index '{index_name}' deleted successfully")
      return True
  
  
  def update_mapping(es_client, index_name: str, new_fields: Dict[str, Any]) -> bool:
      """
      Update mapping for existing index (only adding new fields).
  
      Args:
          es_client: Elasticsearch client instance
          index_name: Name of the index
          new_fields: New field mappings to add
  
      Returns:
          True if successful
      """
      if not es_client.indices.exists(index=index_name):
          print(f"Index '{index_name}' does not exist")
          return False
  
      mapping = {"properties": new_fields}
      es_client.indices.put_mapping(index=index_name, body=mapping)
      print(f"Mapping updated for index '{index_name}'")
      return True