app.js
16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
213
214
215
216
217
218
219
220
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
// SearchEngine Frontend JavaScript
// API endpoint
const API_BASE_URL = 'http://120.76.41.98:6002';
// Update API URL display
document.getElementById('apiUrl').textContent = API_BASE_URL;
// Handle Enter key in search input
function handleKeyPress(event) {
if (event.key === 'Enter') {
performSearch();
}
}
// Set query from example buttons
function setQuery(query) {
document.getElementById('searchInput').value = query;
performSearch();
}
// 全局变量存储当前的过滤条件
let currentFilters = {};
// Perform search
async function performSearch() {
const query = document.getElementById('searchInput').value.trim();
if (!query) {
alert('请输入搜索关键词');
return;
}
// Get options
const size = parseInt(document.getElementById('resultSize').value);
const sortByValue = document.getElementById('sortBy').value;
// Parse sort option
let sort_by = null;
let sort_order = 'desc';
if (sortByValue) {
const [field, order] = sortByValue.split(':');
sort_by = field;
sort_order = order;
}
// Define aggregations for faceted search
const aggregations = {
"category_stats": {
"terms": {
"field": "categoryName_keyword",
"size": 10
}
},
"brand_stats": {
"terms": {
"field": "brandName_keyword",
"size": 10
}
},
"supplier_stats": {
"terms": {
"field": "supplierName_keyword",
"size": 10
}
},
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{"key": "0-50", "to": 50},
{"key": "50-100", "from": 50, "to": 100},
{"key": "100-200", "from": 100, "to": 200},
{"key": "200+", "from": 200}
]
}
}
};
// Show loading
document.getElementById('loading').style.display = 'block';
document.getElementById('results').innerHTML = '';
document.getElementById('queryInfo').innerHTML = '';
document.getElementById('aggregationResults').innerHTML = '';
try {
const response = await fetch(`${API_BASE_URL}/search/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: query,
size: size,
filters: Object.keys(currentFilters).length > 0 ? currentFilters : null,
aggregations: aggregations,
sort_by: sort_by,
sort_order: sort_order
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
displayResults(data);
displayQueryInfo(data.query_info);
displayAggregations(data.aggregations);
displayActiveFilters();
} catch (error) {
console.error('Search error:', error);
document.getElementById('results').innerHTML = `
<div class="error-message">
<strong>搜索出错:</strong> ${error.message}
<br><br>
<small>请确保后端服务正在运行 (${API_BASE_URL})</small>
</div>
`;
} finally {
document.getElementById('loading').style.display = 'none';
}
}
// Display search results
function displayResults(data) {
const resultsDiv = document.getElementById('results');
if (!data.hits || data.hits.length === 0) {
resultsDiv.innerHTML = `
<div class="no-results">
<h3>😔 没有找到结果</h3>
<p>请尝试其他关键词</p>
</div>
`;
return;
}
let html = `
<div class="results-header">
<h2>搜索结果</h2>
<div class="results-stats">
找到 <strong>${data.total}</strong> 个结果,
耗时 <strong>${data.took_ms}</strong> 毫秒,
最高分 <strong>${data.max_score.toFixed(4)}</strong>
</div>
</div>
`;
data.hits.forEach((hit, index) => {
const source = hit._source;
const score = hit._custom_score || hit._score;
html += `
<div class="result-item">
<div class="result-header">
<div>
<div class="result-title">${index + 1}. ${escapeHtml(source.name || 'N/A')}</div>
${source.enSpuName ? `<div style="color: #666; font-size: 14px;">${escapeHtml(source.enSpuName)}</div>` : ''}
${source.ruSkuName ? `<div style="color: #999; font-size: 13px;">${escapeHtml(source.ruSkuName)}</div>` : ''}
</div>
<div class="result-score">
${score.toFixed(4)}
</div>
</div>
<div class="result-meta">
${source.price ? `<span>💰 ¥${escapeHtml(source.price)}</span>` : ''}
${source.categoryName ? `<span>📁 ${escapeHtml(source.categoryName)}</span>` : ''}
${source.brandName ? `<span>🏷️ ${escapeHtml(source.brandName)}</span>` : ''}
${source.supplierName ? `<span>🏭 ${escapeHtml(source.supplierName)}</span>` : ''}
${source.create_time ? `<span>📅 ${formatDate(source.create_time)}</span>` : ''}
</div>
${source.imageUrl ? `
<img src="${escapeHtml(source.imageUrl)}"
alt="${escapeHtml(source.name)}"
class="result-image"
onerror="this.style.display='none'">
` : ''}
<div style="margin-top: 10px; font-size: 12px; color: #999;">
ID: ${source.skuId || 'N/A'}
</div>
</div>
`;
});
resultsDiv.innerHTML = html;
}
// Display query processing information
function displayQueryInfo(queryInfo) {
if (!queryInfo) return;
const queryInfoDiv = document.getElementById('queryInfo');
let html = `
<h3>查询处理信息</h3>
<div class="info-grid">
<div class="info-item">
<strong>原始查询</strong>
${escapeHtml(queryInfo.original_query || 'N/A')}
</div>
<div class="info-item">
<strong>重写后查询</strong>
${escapeHtml(queryInfo.rewritten_query || 'N/A')}
</div>
<div class="info-item">
<strong>检测语言</strong>
${getLanguageName(queryInfo.detected_language)}
</div>
<div class="info-item">
<strong>查询域</strong>
${escapeHtml(queryInfo.domain || 'default')}
</div>
</div>
`;
// Show translations if any
if (queryInfo.translations && Object.keys(queryInfo.translations).length > 0) {
html += '<h4 style="margin-top: 20px; margin-bottom: 10px;">翻译结果</h4><div class="info-grid">';
for (const [lang, translation] of Object.entries(queryInfo.translations)) {
if (translation) {
html += `
<div class="info-item">
<strong>${getLanguageName(lang)}</strong>
${escapeHtml(translation)}
</div>
`;
}
}
html += '</div>';
}
// Show embedding info
if (queryInfo.has_vector) {
html += `
<div style="margin-top: 15px; padding: 10px; background: #e8f5e9; border-radius: 5px;">
✓ 使用了语义向量搜索
</div>
`;
}
queryInfoDiv.innerHTML = html;
}
// Helper functions
function escapeHtml(text) {
if (!text) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatDate(dateStr) {
try {
const date = new Date(dateStr);
return date.toLocaleDateString('zh-CN');
} catch {
return dateStr;
}
}
function getLanguageName(code) {
const names = {
'zh': '中文',
'en': 'English',
'ru': 'Русский',
'ar': 'العربية',
'ja': '日本語',
'unknown': '未知'
};
return names[code] || code;
}
// Display aggregations
function displayAggregations(aggregations) {
if (!aggregations || Object.keys(aggregations).length === 0) {
document.getElementById('aggregationPanel').style.display = 'none';
return;
}
document.getElementById('aggregationPanel').style.display = 'block';
const aggregationResultsDiv = document.getElementById('aggregationResults');
let html = '';
// Category aggregation
if (aggregations.category_stats && aggregations.category_stats.buckets) {
html += `
<div class="aggregation-group">
<h4>商品分类</h4>
<div class="aggregation-items">
`;
aggregations.category_stats.buckets.forEach(bucket => {
const key = bucket.key;
const count = bucket.doc_count;
const isChecked = currentFilters.categoryName_keyword && currentFilters.categoryName_keyword.includes(key);
html += `
<label class="aggregation-item">
<input type="checkbox"
${isChecked ? 'checked' : ''}
onchange="toggleFilter('categoryName_keyword', '${escapeHtml(key)}', this.checked)">
<span>${escapeHtml(key)}</span>
<span class="count">(${count})</span>
</label>
`;
});
html += '</div></div>';
}
// Brand aggregation
if (aggregations.brand_stats && aggregations.brand_stats.buckets) {
html += `
<div class="aggregation-group">
<h4>品牌</h4>
<div class="aggregation-items">
`;
aggregations.brand_stats.buckets.forEach(bucket => {
const key = bucket.key;
const count = bucket.doc_count;
const isChecked = currentFilters.brandName_keyword && currentFilters.brandName_keyword.includes(key);
html += `
<label class="aggregation-item">
<input type="checkbox"
${isChecked ? 'checked' : ''}
onchange="toggleFilter('brandName_keyword', '${escapeHtml(key)}', this.checked)">
<span>${escapeHtml(key)}</span>
<span class="count">(${count})</span>
</label>
`;
});
html += '</div></div>';
}
// Supplier aggregation
if (aggregations.supplier_stats && aggregations.supplier_stats.buckets) {
html += `
<div class="aggregation-group">
<h4>供应商</h4>
<div class="aggregation-items">
`;
aggregations.supplier_stats.buckets.slice(0, 5).forEach(bucket => {
const key = bucket.key;
const count = bucket.doc_count;
const isChecked = currentFilters.supplierName_keyword && currentFilters.supplierName_keyword.includes(key);
html += `
<label class="aggregation-item">
<input type="checkbox"
${isChecked ? 'checked' : ''}
onchange="toggleFilter('supplierName_keyword', '${escapeHtml(key)}', this.checked)">
<span>${escapeHtml(key)}</span>
<span class="count">(${count})</span>
</label>
`;
});
html += '</div></div>';
}
// Price range aggregation
if (aggregations.price_ranges && aggregations.price_ranges.buckets) {
html += `
<div class="aggregation-group">
<h4>价格区间</h4>
<div class="aggregation-items">
`;
aggregations.price_ranges.buckets.forEach(bucket => {
const key = bucket.key;
const count = bucket.doc_count;
const isChecked = currentFilters.price_ranges && currentFilters.price_ranges.includes(key);
const priceLabel = {
'0-50': '¥0-50',
'50-100': '¥50-100',
'100-200': '¥100-200',
'200+': '¥200+'
};
html += `
<label class="aggregation-item">
<input type="checkbox"
${isChecked ? 'checked' : ''}
onchange="togglePriceFilter('${escapeHtml(key)}', this.checked)">
<span>${priceLabel[key] || key}</span>
<span class="count">(${count})</span>
</label>
`;
});
html += '</div></div>';
}
aggregationResultsDiv.innerHTML = html;
}
// Display active filters
function displayActiveFilters() {
const activeFiltersDiv = document.getElementById('activeFilters');
if (Object.keys(currentFilters).length === 0) {
activeFiltersDiv.innerHTML = '';
return;
}
let html = '<div class="active-filters-list">';
Object.entries(currentFilters).forEach(([field, values]) => {
if (Array.isArray(values)) {
values.forEach(value => {
let displayValue = value;
if (field === 'price_ranges') {
const priceLabel = {
'0-50': '¥0-50',
'50-100': '¥50-100',
'100-200': '¥100-200',
'200+': '¥200+'
};
displayValue = priceLabel[value] || value;
}
html += `
<span class="active-filter-tag">
${escapeHtml(displayValue)}
<button onclick="removeFilter('${field}', '${escapeHtml(value)}')" class="remove-filter">×</button>
</span>
`;
});
}
});
html += `<button onclick="clearAllFilters()" class="clear-filters">清除所有</button></div>`;
activeFiltersDiv.innerHTML = html;
}
// Toggle filter
function toggleFilter(field, value, checked) {
if (checked) {
if (!currentFilters[field]) {
currentFilters[field] = [];
}
if (!currentFilters[field].includes(value)) {
currentFilters[field].push(value);
}
} else {
if (currentFilters[field]) {
const index = currentFilters[field].indexOf(value);
if (index > -1) {
currentFilters[field].splice(index, 1);
}
if (currentFilters[field].length === 0) {
delete currentFilters[field];
}
}
}
// Re-run search with new filters
performSearch();
}
// Toggle price filter
function togglePriceFilter(value, checked) {
if (checked) {
if (!currentFilters.price_ranges) {
currentFilters.price_ranges = [];
}
if (!currentFilters.price_ranges.includes(value)) {
currentFilters.price_ranges.push(value);
}
} else {
if (currentFilters.price_ranges) {
const index = currentFilters.price_ranges.indexOf(value);
if (index > -1) {
currentFilters.price_ranges.splice(index, 1);
}
if (currentFilters.price_ranges.length === 0) {
delete currentFilters.price_ranges;
}
}
}
// Re-run search with new filters
performSearch();
}
// Remove single filter
function removeFilter(field, value) {
toggleFilter(field, value, false);
}
// Clear all filters
function clearAllFilters() {
currentFilters = {};
performSearch();
}
// Initialize page
document.addEventListener('DOMContentLoaded', function() {
console.log('SearchEngine Frontend loaded');
console.log('API Base URL:', API_BASE_URL);
// Focus on search input
document.getElementById('searchInput').focus();
});