be52af70
tangwang
first commit
|
1
2
3
4
|
"""
Search API routes.
"""
|
16c42787
tangwang
feat: implement r...
|
5
|
from fastapi import APIRouter, HTTPException, Query, Request
|
be52af70
tangwang
first commit
|
6
|
from typing import Optional
|
16c42787
tangwang
feat: implement r...
|
7
|
import uuid
|
be52af70
tangwang
first commit
|
8
9
10
11
12
|
from ..models import (
SearchRequest,
ImageSearchRequest,
SearchResponse,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
13
|
SearchSuggestResponse,
|
be52af70
tangwang
first commit
|
14
15
16
|
DocumentResponse,
ErrorResponse
)
|
16c42787
tangwang
feat: implement r...
|
17
|
from context.request_context import create_request_context, set_current_request_context, clear_current_request_context
|
be52af70
tangwang
first commit
|
18
19
20
21
|
router = APIRouter(prefix="/search", tags=["search"])
|
16c42787
tangwang
feat: implement r...
|
22
23
24
25
26
27
28
29
30
31
32
|
def extract_request_info(request: Request) -> tuple[str, str]:
"""Extract request ID and user ID from HTTP request"""
# Try to get request ID from headers
reqid = request.headers.get('X-Request-ID') or str(uuid.uuid4())[:8]
# Try to get user ID from headers or default to anonymous
uid = request.headers.get('X-User-ID') or request.headers.get('User-ID') or 'anonymous'
return reqid, uid
|
be52af70
tangwang
first commit
|
33
|
@router.post("/", response_model=SearchResponse)
|
16c42787
tangwang
feat: implement r...
|
34
|
async def search(request: SearchRequest, http_request: Request):
|
be52af70
tangwang
first commit
|
35
|
"""
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
36
|
Execute text search query (外部友好格式).
|
be52af70
tangwang
first commit
|
37
38
39
40
41
42
|
Supports:
- Multi-language query processing
- Boolean operators (AND, OR, RANK, ANDNOT)
- Semantic search with embeddings
- Custom ranking functions
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
43
44
|
- Exact match filters and range filters
- Faceted search
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
45
46
|
Requires tenant_id in header (X-Tenant-ID) or query parameter (tenant_id).
|
be52af70
tangwang
first commit
|
47
|
"""
|
16c42787
tangwang
feat: implement r...
|
48
49
|
reqid, uid = extract_request_info(http_request)
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# Extract tenant_id (required)
tenant_id = http_request.headers.get('X-Tenant-ID')
if not tenant_id:
# Try to get from query string
from urllib.parse import parse_qs
query_string = http_request.url.query
if query_string:
params = parse_qs(query_string)
tenant_id = params.get('tenant_id', [None])[0]
if not tenant_id:
raise HTTPException(
status_code=400,
detail="tenant_id is required. Provide it via header 'X-Tenant-ID' or query parameter 'tenant_id'"
)
|
16c42787
tangwang
feat: implement r...
|
66
67
68
69
70
|
# Create request context
context = create_request_context(reqid=reqid, uid=uid)
# Set context in thread-local storage
set_current_request_context(context)
|
be52af70
tangwang
first commit
|
71
72
|
try:
|
16c42787
tangwang
feat: implement r...
|
73
74
|
# Log request start
context.logger.info(
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
75
|
f"收到搜索请求 | Tenant: {tenant_id} | IP: {http_request.client.host if http_request.client else 'unknown'} | "
|
16c42787
tangwang
feat: implement r...
|
76
77
78
79
|
f"用户代理: {http_request.headers.get('User-Agent', 'unknown')[:100]}",
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
be52af70
tangwang
first commit
|
80
|
# Get searcher from app state
|
bb3c5ef8
tangwang
灌入数据流程跑通
|
81
|
from api.app import get_searcher
|
be52af70
tangwang
first commit
|
82
83
|
searcher = get_searcher()
|
16c42787
tangwang
feat: implement r...
|
84
|
# Execute search with context (using backend defaults from config)
|
be52af70
tangwang
first commit
|
85
86
|
result = searcher.search(
query=request.query,
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
87
|
tenant_id=tenant_id,
|
be52af70
tangwang
first commit
|
88
89
90
|
size=request.size,
from_=request.from_,
filters=request.filters,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
91
92
|
range_filters=request.range_filters,
facets=request.facets,
|
16c42787
tangwang
feat: implement r...
|
93
|
min_score=request.min_score,
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
94
|
context=context,
|
c86c8237
tangwang
支持聚合。过滤项补充了逻辑,但是有问题
|
95
|
sort_by=request.sort_by,
|
1f071951
tangwang
补充调试信息,记录包括各个阶段的 ...
|
96
|
sort_order=request.sort_order,
|
577ec972
tangwang
返回给前端的字段、格式适配。主要包...
|
97
98
|
debug=request.debug,
language=request.language,
|
be52af70
tangwang
first commit
|
99
100
|
)
|
16c42787
tangwang
feat: implement r...
|
101
102
103
|
# Include performance summary in response
performance_summary = context.get_summary() if context else None
|
be52af70
tangwang
first commit
|
104
105
|
# Convert to response model
return SearchResponse(
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
106
|
results=result.results,
|
be52af70
tangwang
first commit
|
107
108
109
|
total=result.total,
max_score=result.max_score,
took_ms=result.took_ms,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
110
|
facets=result.facets,
|
16c42787
tangwang
feat: implement r...
|
111
|
query_info=result.query_info,
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
112
113
|
suggestions=result.suggestions,
related_searches=result.related_searches,
|
1f071951
tangwang
补充调试信息,记录包括各个阶段的 ...
|
114
115
|
performance_info=performance_summary,
debug_info=result.debug_info
|
be52af70
tangwang
first commit
|
116
117
118
|
)
except Exception as e:
|
16c42787
tangwang
feat: implement r...
|
119
120
121
122
123
124
125
|
# Log error in context
if context:
context.set_error(e)
context.logger.error(
f"搜索请求失败 | 错误: {str(e)}",
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
be52af70
tangwang
first commit
|
126
|
raise HTTPException(status_code=500, detail=str(e))
|
16c42787
tangwang
feat: implement r...
|
127
128
129
|
finally:
# Clear thread-local context
clear_current_request_context()
|
be52af70
tangwang
first commit
|
130
131
132
|
@router.post("/image", response_model=SearchResponse)
|
16c42787
tangwang
feat: implement r...
|
133
|
async def search_by_image(request: ImageSearchRequest, http_request: Request):
|
be52af70
tangwang
first commit
|
134
|
"""
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
135
|
Search by image similarity (外部友好格式).
|
be52af70
tangwang
first commit
|
136
137
|
Uses image embeddings to find visually similar products.
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
138
|
Supports exact match filters and range filters.
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
139
140
|
Requires tenant_id in header (X-Tenant-ID) or query parameter (tenant_id).
|
be52af70
tangwang
first commit
|
141
|
"""
|
16c42787
tangwang
feat: implement r...
|
142
143
|
reqid, uid = extract_request_info(http_request)
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
|
# Extract tenant_id (required)
tenant_id = http_request.headers.get('X-Tenant-ID')
if not tenant_id:
from urllib.parse import parse_qs
query_string = http_request.url.query
if query_string:
params = parse_qs(query_string)
tenant_id = params.get('tenant_id', [None])[0]
if not tenant_id:
raise HTTPException(
status_code=400,
detail="tenant_id is required. Provide it via header 'X-Tenant-ID' or query parameter 'tenant_id'"
)
|
16c42787
tangwang
feat: implement r...
|
159
160
161
162
163
164
|
# Create request context
context = create_request_context(reqid=reqid, uid=uid)
# Set context in thread-local storage
set_current_request_context(context)
|
be52af70
tangwang
first commit
|
165
|
try:
|
16c42787
tangwang
feat: implement r...
|
166
167
|
# Log request start
context.logger.info(
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
168
|
f"收到图片搜索请求 | Tenant: {tenant_id} | 图片URL: {request.image_url} | "
|
16c42787
tangwang
feat: implement r...
|
169
170
171
172
|
f"IP: {http_request.client.host if http_request.client else 'unknown'}",
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
bb3c5ef8
tangwang
灌入数据流程跑通
|
173
|
from api.app import get_searcher
|
be52af70
tangwang
first commit
|
174
175
176
177
178
|
searcher = get_searcher()
# Execute image search
result = searcher.search_by_image(
image_url=request.image_url,
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
179
|
tenant_id=tenant_id,
|
be52af70
tangwang
first commit
|
180
|
size=request.size,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
181
182
|
filters=request.filters,
range_filters=request.range_filters
|
be52af70
tangwang
first commit
|
183
184
|
)
|
16c42787
tangwang
feat: implement r...
|
185
186
187
|
# Include performance summary in response
performance_summary = context.get_summary() if context else None
|
be52af70
tangwang
first commit
|
188
|
return SearchResponse(
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
189
|
results=result.results,
|
be52af70
tangwang
first commit
|
190
191
192
|
total=result.total,
max_score=result.max_score,
took_ms=result.took_ms,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
193
|
facets=result.facets,
|
16c42787
tangwang
feat: implement r...
|
194
|
query_info=result.query_info,
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
195
196
|
suggestions=result.suggestions,
related_searches=result.related_searches,
|
16c42787
tangwang
feat: implement r...
|
197
|
performance_info=performance_summary
|
be52af70
tangwang
first commit
|
198
199
200
|
)
except ValueError as e:
|
16c42787
tangwang
feat: implement r...
|
201
202
203
204
205
206
|
if context:
context.set_error(e)
context.logger.error(
f"图片搜索请求参数错误 | 错误: {str(e)}",
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
be52af70
tangwang
first commit
|
207
208
|
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
|
16c42787
tangwang
feat: implement r...
|
209
210
211
212
213
214
|
if context:
context.set_error(e)
context.logger.error(
f"图片搜索请求失败 | 错误: {str(e)}",
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
be52af70
tangwang
first commit
|
215
|
raise HTTPException(status_code=500, detail=str(e))
|
16c42787
tangwang
feat: implement r...
|
216
217
218
|
finally:
# Clear thread-local context
clear_current_request_context()
|
be52af70
tangwang
first commit
|
219
220
|
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
@router.get("/suggestions", response_model=SearchSuggestResponse)
async def search_suggestions(
q: str = Query(..., min_length=1, description="搜索查询"),
size: int = Query(5, ge=1, le=20, description="建议数量"),
types: str = Query("query", description="建议类型(逗号分隔): query, product, category, brand")
):
"""
获取搜索建议(自动补全)。
功能说明:
- 查询建议(query):基于历史搜索和热门搜索
- 商品建议(product):匹配的商品
- 类目建议(category):匹配的类目
- 品牌建议(brand):匹配的品牌
注意:此功能暂未实现,仅返回框架响应。
"""
import time
start_time = time.time()
# TODO: 实现搜索建议逻辑
# 1. 从搜索历史中获取建议
# 2. 从商品标题中匹配前缀
# 3. 从类目、品牌中匹配
# 临时返回空结果
suggestions = []
# 示例结构(暂不实现):
# suggestions = [
# {
# "text": "芭比娃娃",
# "type": "query",
# "highlight": "<em>芭</em>比娃娃",
# "popularity": 850
# }
# ]
took_ms = int((time.time() - start_time) * 1000)
return SearchSuggestResponse(
query=q,
suggestions=suggestions,
took_ms=took_ms
)
@router.get("/instant", response_model=SearchResponse)
async def instant_search(
q: str = Query(..., min_length=2, description="搜索查询"),
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
271
272
|
size: int = Query(5, ge=1, le=20, description="结果数量"),
tenant_id: str = Query(..., description="租户ID")
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
|
):
"""
即时搜索(Instant Search)。
功能说明:
- 边输入边搜索,无需点击搜索按钮
- 返回简化的搜索结果
注意:此功能暂未实现,调用标准搜索接口。
TODO: 优化即时搜索性能
- 添加防抖/节流
- 实现结果缓存
- 简化返回字段
"""
from api.app import get_searcher
searcher = get_searcher()
result = searcher.search(
query=q,
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
292
|
tenant_id=tenant_id,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
293
294
295
296
297
|
size=size,
from_=0
)
return SearchResponse(
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
298
|
results=result.results,
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
299
300
301
302
|
total=result.total,
max_score=result.max_score,
took_ms=result.took_ms,
facets=result.facets,
|
1f6d15fa
tangwang
重构:SPU级别索引、统一索引架构...
|
303
304
305
|
query_info=result.query_info,
suggestions=result.suggestions,
related_searches=result.related_searches
|
6aa246be
tangwang
问题:Pydantic 应该能自动...
|
306
307
308
|
)
|
be52af70
tangwang
first commit
|
309
310
311
312
313
314
|
@router.get("/{doc_id}", response_model=DocumentResponse)
async def get_document(doc_id: str):
"""
Get a single document by ID.
"""
try:
|
bb3c5ef8
tangwang
灌入数据流程跑通
|
315
|
from api.app import get_searcher
|
be52af70
tangwang
first commit
|
316
317
318
319
320
321
322
323
324
325
326
327
328
|
searcher = get_searcher()
doc = searcher.get_document(doc_id)
if doc is None:
raise HTTPException(status_code=404, detail=f"Document {doc_id} not found")
return DocumentResponse(id=doc_id, source=doc)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
|