test_complete_search.py
6.96 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
#!/usr/bin/env python3
"""
Complete test script simulating frontend search interaction
"""
import requests
import json
API_BASE_URL = 'http://120.76.41.98:6002'
def test_complete_search_workflow():
"""Test complete search workflow similar to frontend"""
print("=" * 60)
print("完整搜索流程测试")
print("=" * 60)
# Step 1: Initial search with aggregations
print("\n1️⃣ 初始搜索(带聚合功能)")
print("-" * 30)
search_request = {
"query": "芭比娃娃",
"size": 10,
"aggregations": {
"category_stats": {
"terms": {
"field": "categoryName_keyword",
"size": 10
}
},
"brand_stats": {
"terms": {
"field": "brandName_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}
]
}
}
}
}
try:
response = requests.post(f"{API_BASE_URL}/search/", json=search_request)
if response.ok:
data = response.json()
print(f"✅ 找到 {data['total']} 个结果,耗时 {data['took_ms']}ms")
# Show aggregations results
if data.get('aggregations'):
print("\n📊 聚合结果:")
# Category aggregations
if 'category_stats' in data['aggregations']:
print(" 🏷️ 分类统计:")
for bucket in data['aggregations']['category_stats']['buckets'][:3]:
print(f" - {bucket['key']}: {bucket['doc_count']} 个商品")
# Brand aggregations
if 'brand_stats' in data['aggregations']:
print(" 🏢 品牌统计:")
for bucket in data['aggregations']['brand_stats']['buckets'][:3]:
print(f" - {bucket['key']}: {bucket['doc_count']} 个商品")
# Price ranges
if 'price_ranges' in data['aggregations']:
print(" 💰 价格分布:")
for bucket in data['aggregations']['price_ranges']['buckets']:
print(f" - {bucket['key']}: {bucket['doc_count']} 个商品")
# Show sample results
print(f"\n🔍 前3个搜索结果:")
for i, hit in enumerate(data['hits'][:3]):
source = hit['_source']
price = source.get('price', 'N/A')
category = source.get('categoryName', 'N/A')
brand = source.get('brandName', 'N/A')
print(f" {i+1}. {source.get('name', 'N/A')}")
print(f" 💰 价格: {price}")
print(f" 📁 分类: {category}")
print(f" 🏷️ 品牌: {brand}")
print(f" ⭐ 评分: {hit['_score']:.3f}")
print()
else:
print(f"❌ 搜索失败: {response.status_code}")
print(f"错误信息: {response.text}")
except Exception as e:
print(f"❌ 请求异常: {e}")
# Step 2: Search with filters
print("\n2️⃣ 带过滤条件的搜索")
print("-" * 30)
filtered_search = {
"query": "芭比娃娃",
"size": 5,
"filters": {
"brandName_keyword": ["美泰"],
"price_ranges": ["50-100", "100-200"]
}
}
try:
response = requests.post(f"{API_BASE_URL}/search/", json=filtered_search)
if response.ok:
data = response.json()
print(f"✅ 过滤后找到 {data['total']} 个结果,耗时 {data['took_ms']}ms")
print(" 🎯 过滤条件: 品牌=美泰, 价格=¥50-200")
print(f"\n💫 前3个过滤结果:")
for i, hit in enumerate(data['hits'][:3]):
source = hit['_source']
price = source.get('price', 'N/A')
category = source.get('categoryName', 'N/A')
brand = source.get('brandName', 'N/A')
print(f" {i+1}. {source.get('name', 'N/A')}")
print(f" 💰 ¥{price} | 📁 {category} | 🏷️ {brand}")
print(f" ⭐ 评分: {hit['_score']:.3f}")
else:
print(f"❌ 过滤搜索失败: {response.status_code}")
except Exception as e:
print(f"❌ 请求异常: {e}")
# Step 3: Search with sorting
print("\n3️⃣ 排序搜索")
print("-" * 30)
# Test price ascending
price_asc_search = {
"query": "芭比娃娃",
"size": 3,
"sort_by": "price",
"sort_order": "asc"
}
try:
response = requests.post(f"{API_BASE_URL}/search/", json=price_asc_search)
if response.ok:
data = response.json()
print(f"✅ 价格升序排序,找到 {data['total']} 个结果")
print(" 📈 排序方式: 价格从低到高")
print(f"\n💵 价格排序结果:")
for i, hit in enumerate(data['hits']):
source = hit['_source']
price = source.get('price', 'N/A')
name = source.get('name', 'N/A')
print(f" {i+1}. ¥{price} - {name}")
else:
print(f"❌ 排序搜索失败: {response.status_code}")
except Exception as e:
print(f"❌ 请求异常: {e}")
# Step 4: Test time sorting
print("\n4️⃣ 时间排序测试")
print("-" * 30)
time_sort_search = {
"query": "芭比娃娃",
"size": 3,
"sort_by": "create_time",
"sort_order": "desc"
}
try:
response = requests.post(f"{API_BASE_URL}/search/", json=time_sort_search)
if response.ok:
data = response.json()
print(f"✅ 时间降序排序,找到 {data['total']} 个结果")
print(" 📅 排序方式: 上架时间从新到旧")
print(f"\n🕐 时间排序结果:")
for i, hit in enumerate(data['hits']):
source = hit['_source']
create_time = source.get('create_time', 'N/A')
name = source.get('name', 'N/A')
print(f" {i+1}. {create_time} - {name}")
else:
print(f"❌ 时间排序失败: {response.status_code}")
except Exception as e:
print(f"❌ 请求异常: {e}")
print("\n" + "=" * 60)
print("🎉 搜索功能测试完成!")
print("✨ 前端访问地址: http://localhost:8080")
print("🔧 后端API地址: http://120.76.41.98:6002")
print("=" * 60)
if __name__ == "__main__":
test_complete_search_workflow()