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
|
"""
from typing import Dict, Any
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
8
9
|
import logging
|
be52af70
tangwang
first commit
|
10
|
from config import (
|
9cb7528e
tangwang
店匠体系数据的搜索:mock da...
|
11
|
SearchConfig,
|
be52af70
tangwang
first commit
|
12
13
14
15
16
17
|
FieldConfig,
get_es_mapping_for_field,
get_default_analyzers,
get_default_similarity
)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
18
19
|
logger = logging.getLogger(__name__)
|
be52af70
tangwang
first commit
|
20
21
|
class MappingGenerator:
|
9cb7528e
tangwang
店匠体系数据的搜索:mock da...
|
22
|
"""Generates Elasticsearch mapping from search configuration."""
|
be52af70
tangwang
first commit
|
23
|
|
9cb7528e
tangwang
店匠体系数据的搜索:mock da...
|
24
|
def __init__(self, config: SearchConfig):
|
be52af70
tangwang
first commit
|
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
|
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:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
92
|
Field name or empty string if not configured
|
be52af70
tangwang
first commit
|
93
|
"""
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
94
|
return self.config.query_config.text_embedding_field or ""
|
be52af70
tangwang
first commit
|
95
96
97
98
99
100
|
def get_image_embedding_field(self) -> str:
"""
Get the primary image embedding field name.
Returns:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
101
|
Field name or empty string if not configured
|
be52af70
tangwang
first commit
|
102
|
"""
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
103
|
return self.config.query_config.image_embedding_field or ""
|
be52af70
tangwang
first commit
|
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
|
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):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
156
|
logger.info(f"Index '{index_name}' already exists")
|
be52af70
tangwang
first commit
|
157
158
159
|
return False
es_client.indices.create(index=index_name, body=mapping)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
160
|
logger.info(f"Index '{index_name}' created successfully")
|
be52af70
tangwang
first commit
|
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
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):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
176
|
logger.warning(f"Index '{index_name}' does not exist")
|
be52af70
tangwang
first commit
|
177
178
179
|
return False
es_client.indices.delete(index=index_name)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
180
|
logger.info(f"Index '{index_name}' deleted successfully")
|
be52af70
tangwang
first commit
|
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
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):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
197
|
logger.error(f"Index '{index_name}' does not exist")
|
be52af70
tangwang
first commit
|
198
199
200
201
|
return False
mapping = {"properties": new_fields}
es_client.indices.put_mapping(index=index_name, body=mapping)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
202
|
logger.info(f"Mapping updated for index '{index_name}'")
|
be52af70
tangwang
first commit
|
203
|
return True
|