-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsearch_test.py
More file actions
195 lines (155 loc) · 6.12 KB
/
Copy pathsearch_test.py
File metadata and controls
195 lines (155 loc) · 6.12 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
#!/usr/bin/env python3
"""
Google Retail API performance testing script.
Measures search performance by executing queries and reporting timing metrics.
"""
import sys
import time
from pathlib import Path
from typing import List
from google.cloud.retail_v2 import SearchRequest, SearchServiceClient
from google.api_core import exceptions
from google.oauth2 import service_account
# --- Configuration ---
PROJECT_ID = ""
KEY_FILE = "path to keyfile.json"
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
LOCATION = "global"
CATALOG = "default_catalog"
PLACEMENT = "default_search"
QUERY_FILE = "queries.txt"
VISITOR_ID = "12345"
PAGE_SIZE = 100
FILTER = 'availability: ANY("IN_STOCK")'
QUERY_EXPANSION = {'condition':'AUTO'}
def validate_configuration():
"""Validate that required configuration is set."""
if not PROJECT_ID:
print("Error: PROJECT_ID is not set.")
return False
if not Path(KEY_FILE).exists():
print(f"Error: Service account key file not found at '{KEY_FILE}'")
return False
if not Path(QUERY_FILE).exists():
print(f"Error: Query file not found at '{QUERY_FILE}'")
return False
return True
def create_credentials():
"""Create credentials from service account key file."""
try:
credentials = service_account.Credentials.from_service_account_file(
KEY_FILE,
scopes=SCOPES
)
return credentials
except Exception as e:
print(f"Error loading credentials: {e}")
return None
def read_queries(query_file: str) -> List[str]:
"""Read search queries from file, one per line."""
queries = []
with open(query_file, 'r', encoding='utf-8') as f:
for line in f:
query = line.strip()
if query:
queries.append(query)
return queries
def perform_search(client: SearchServiceClient, placement_path: str, query: str) -> tuple:
"""Perform a single search request and return (result_count, duration_ms, success)."""
start_time = time.time()
try:
request = SearchRequest(
placement=placement_path,
visitor_id=VISITOR_ID,
query=query,
page_size=PAGE_SIZE,
query_expansion_spec=QUERY_EXPANSION,
filter=FILTER
)
response_pager = client.search(request=request)
first_page = next(iter(response_pager.pages))
result_count = len(first_page.results)
end_time = time.time()
duration_ms = (end_time - start_time) * 1000
return result_count, duration_ms, True
except exceptions.GoogleAPIError as e:
end_time = time.time()
duration_ms = (end_time - start_time) * 1000
print(f" ✗ API Error: {e}")
return 0, duration_ms, False
except Exception as e:
end_time = time.time()
duration_ms = (end_time - start_time) * 1000
print(f" ✗ Error: {e}")
return 0, duration_ms, False
def main():
"""Main function to execute the performance test."""
print("Google Retail API Performance Test")
print("=" * 50)
# Validate configuration
if not validate_configuration():
sys.exit(1)
# Read queries
try:
queries = read_queries(QUERY_FILE)
except Exception as e:
print(f"Error reading query file: {e}")
sys.exit(1)
if not queries:
print(f"No queries found in '{QUERY_FILE}'. Exiting.")
sys.exit(0)
print(f"Found {len(queries)} queries to test")
# Initialize client
try:
credentials = create_credentials()
if not credentials:
sys.exit(1)
client = SearchServiceClient(credentials=credentials)
print("✓ Client initialized successfully")
except Exception as e:
print(f"Error initializing client: {e}")
sys.exit(1)
# Build placement path
placement_path = f"projects/{PROJECT_ID}/locations/{LOCATION}/catalogs/{CATALOG}/placements/{PLACEMENT}"
print(f"Using placement: {placement_path}")
print("-" * 50)
# Execute searches and collect metrics
total_start_time = time.time()
successful_searches = 0
failed_searches = 0
total_results = 0
durations = []
for i, query in enumerate(queries, 1):
print(f"[{i:3d}/{len(queries)}] Testing: '{query[:50]}{'...' if len(query) > 50 else ''}'")
result_count, duration_ms, success = perform_search(client, placement_path, query)
durations.append(duration_ms)
if success:
successful_searches += 1
total_results += result_count
print(f" ✓ {result_count} results in {duration_ms:.1f}ms")
else:
failed_searches += 1
print(f" ✗ Failed in {duration_ms:.1f}ms")
total_end_time = time.time()
total_duration_seconds = total_end_time - total_start_time
# Print performance summary
print("\n" + "=" * 50)
print("PERFORMANCE SUMMARY")
print("=" * 50)
print(f"Total queries processed: {len(queries)}")
print(f"Successful searches: {successful_searches}")
print(f"Failed searches: {failed_searches}")
print(f"Total results found: {total_results}")
print(f"Average results per query: {total_results / successful_searches if successful_searches > 0 else 0:.1f}")
print()
print(f"Total execution time: {total_duration_seconds:.2f} seconds")
print(f"Average time per request: {sum(durations) / len(durations):.1f} ms")
print(f"Fastest request: {min(durations):.1f} ms")
print(f"Slowest request: {max(durations):.1f} ms")
print(f"Requests per second: {len(queries) / total_duration_seconds:.2f}")
if successful_searches > 0:
successful_durations = [durations[i] for i, query in enumerate(queries)
if perform_search(client, placement_path, query)[2]]
print(f"Avg time (successful only): {sum(d for d in durations if d > 0) / successful_searches:.1f} ms")
if __name__ == "__main__":
main()