Blame view

test_aggregation_api.py 5.47 KB
c86c8237   tangwang   支持聚合。过滤项补充了逻辑,但是有问题
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
  #!/usr/bin/env python3
  """
  Test script for aggregation functionality
  """
  
  import requests
  import json
  
  API_BASE_URL = 'http://120.76.41.98:6002'
  
  def test_search_with_aggregations():
      """Test search with aggregations"""
  
      # Test data
      test_query = {
          "query": "玩具",
          "size": 5,
          "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}
                      ]
                  }
              }
          }
      }
  
      print("Testing search with aggregations...")
      print(f"Query: {json.dumps(test_query, indent=2, ensure_ascii=False)}")
  
      try:
          response = requests.post(f"{API_BASE_URL}/search/",
                                 json=test_query,
                                 headers={'Content-Type': 'application/json'})
  
          print(f"Status Code: {response.status_code}")
  
          if response.ok:
              data = response.json()
              print(f"Found {data['total']} results in {data['took_ms']}ms")
              print(f"Max Score: {data['max_score']}")
  
              # Print aggregations
              if data.get('aggregations'):
                  print("\nAggregations:")
                  for agg_name, agg_result in data['aggregations'].items():
                      print(f"\n{agg_name}:")
                      if 'buckets' in agg_result:
                          for bucket in agg_result['buckets'][:5]:  # Show first 5 buckets
                              print(f"  - {bucket['key']}: {bucket['doc_count']}")
  
              # Print first few results
              print(f"\nFirst 3 results:")
              for i, hit in enumerate(data['hits'][:3]):
                  source = hit['_source']
                  print(f"\n{i+1}. {source.get('name', 'N/A')}")
                  print(f"   Category: {source.get('categoryName', 'N/A')}")
                  print(f"   Brand: {source.get('brandName', 'N/A')}")
                  print(f"   Price: {source.get('price', 'N/A')}")
                  print(f"   Score: {hit['_score']:.4f}")
          else:
              print(f"Error: {response.status_code}")
              print(f"Response: {response.text}")
  
      except Exception as e:
          print(f"Request failed: {e}")
  
  def test_search_with_filters():
      """Test search with filters"""
  
      test_filters = {
          "query": "玩具",
          "size": 5,
          "filters": {
              "categoryName_keyword": ["玩具"],
              "price_ranges": ["0-50", "50-100"]
          }
      }
  
      print("\n\nTesting search with filters...")
      print(f"Query: {json.dumps(test_filters, indent=2, ensure_ascii=False)}")
  
      try:
          response = requests.post(f"{API_BASE_URL}/search/",
                                 json=test_filters,
                                 headers={'Content-Type': 'application/json'})
  
          print(f"Status Code: {response.status_code}")
  
          if response.ok:
              data = response.json()
              print(f"Found {data['total']} results in {data['took_ms']}ms")
  
              print(f"\nFirst 3 results:")
              for i, hit in enumerate(data['hits'][:3]):
                  source = hit['_source']
                  print(f"\n{i+1}. {source.get('name', 'N/A')}")
                  print(f"   Category: {source.get('categoryName', 'N/A')}")
                  print(f"   Brand: {source.get('brandName', 'N/A')}")
                  print(f"   Price: {source.get('price', 'N/A')}")
                  print(f"   Score: {hit['_score']:.4f}")
          else:
              print(f"Error: {response.status_code}")
              print(f"Response: {response.text}")
  
      except Exception as e:
          print(f"Request failed: {e}")
  
  def test_search_with_sorting():
      """Test search with sorting"""
  
      test_sort = {
          "query": "玩具",
          "size": 5,
          "sort_by": "price",
          "sort_order": "asc"
      }
  
      print("\n\nTesting search with sorting (price ascending)...")
      print(f"Query: {json.dumps(test_sort, indent=2, ensure_ascii=False)}")
  
      try:
          response = requests.post(f"{API_BASE_URL}/search/",
                                 json=test_sort,
                                 headers={'Content-Type': 'application/json'})
  
          print(f"Status Code: {response.status_code}")
  
          if response.ok:
              data = response.json()
              print(f"Found {data['total']} results in {data['took_ms']}ms")
  
              print(f"\nFirst 3 results (sorted by price):")
              for i, hit in enumerate(data['hits'][:3]):
                  source = hit['_source']
                  print(f"\n{i+1}. {source.get('name', 'N/A')}")
                  print(f"   Price: {source.get('price', 'N/A')}")
                  print(f"   Score: {hit['_score']:.4f}")
          else:
              print(f"Error: {response.status_code}")
              print(f"Response: {response.text}")
  
      except Exception as e:
          print(f"Request failed: {e}")
  
  if __name__ == "__main__":
      test_search_with_aggregations()
      test_search_with_filters()
      test_search_with_sorting()