-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathsearch.py
More file actions
309 lines (271 loc) · 11.6 KB
/
search.py
File metadata and controls
309 lines (271 loc) · 11.6 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
import logging
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, Query
from feast.api.registry.rest.rest_utils import (
filter_search_results_and_match_score,
get_all_project_resources,
list_all_projects,
paginate_and_sort,
parse_tags,
validate_or_set_default_pagination_params,
validate_or_set_default_sorting_params,
)
logger = logging.getLogger(__name__)
custom_sorting = validate_or_set_default_sorting_params(
sort_by_options=["match_score", "name", "type"],
default_sort_by_option="match_score",
default_sort_order="desc",
)
custom_pagination = validate_or_set_default_pagination_params(
default_page=1,
default_limit=50,
)
def get_search_router(grpc_handler) -> APIRouter:
router = APIRouter()
@router.get("/search")
def search_resources(
query: str = Query(..., description="Search query string"),
projects: Optional[List[str]] = Query(
default=[],
description="Project names to search in (optional - searches all projects if not specified)",
),
allow_cache: bool = Query(default=True),
tags: Dict[str, str] = Depends(parse_tags),
sorting_params: dict = Depends(custom_sorting),
pagination_params: dict = Depends(custom_pagination),
) -> Dict[str, Any]:
"""
Search across all Feast resources including:
- Entities
- Feature Views
- Features
- Feature Services
- Data Sources
- Saved Datasets
Project Selection:
- No projects parameter: Search all projects (default)
- projects=["proj1"]: Search single project
- projects=["proj1", "proj2"]: Search multiple projects
Sorting:
- Supports sorting by match_score, name, or type
- Can specify sort_order as asc or desc
"""
results = []
errors = []
# Get list of all available projects for validation
err_msg = ""
projects_to_search, err_msg = _validate_projects(
projects, grpc_handler, allow_cache
)
if err_msg:
errors.append(err_msg)
if not projects_to_search:
return {
"query": query,
"projects_searched": projects_to_search,
"results": [],
"pagination": {},
"errors": errors,
}
# Search across all specified projects using helper function
for current_project in projects_to_search:
try:
# Get all resources for this project
project_resources, _, resource_errors = get_all_project_resources(
grpc_handler,
current_project,
allow_cache,
tags,
None,
sorting_params,
)
errors.extend(resource_errors)
# Extract and convert entities
entities = project_resources.get("entities", [])
for entity in entities:
results.append(
{
"type": "entity",
"name": entity.get("spec", {}).get("name", ""),
"description": entity.get("spec", {}).get(
"description", ""
),
"project": current_project,
"tags": entity.get("spec", {}).get("tags", {}),
}
)
# Extract and convert data sources
data_sources = project_resources.get("dataSources", [])
for ds in data_sources:
results.append(
{
"type": "dataSource",
"name": ds.get("dataSource", {}).get("name", "")
or ds.get("name", ""),
"description": ds.get("dataSource", {}).get(
"description", ""
)
or ds.get("description", ""),
"project": current_project,
"tags": ds.get("dataSource", {}).get("tags", {})
or ds.get("tags", {}),
}
)
# Extract and convert feature views (all types - future-proof)
feature_views = project_resources.get("featureViews", [])
for fv in feature_views:
# Find the feature view data by looking for keys that contain "feature" and "view"
feature_view_data = None
for key, value in fv.items():
if (
isinstance(value, dict)
and "feature" in key.lower()
and "view" in key.lower()
):
feature_view_data = value
break
if feature_view_data:
results.append(
{
"type": "featureView",
"name": feature_view_data.get("spec", {}).get(
"name", ""
),
"description": feature_view_data.get("spec", {}).get(
"description", ""
),
"project": current_project,
"tags": feature_view_data.get("spec", {}).get(
"tags", {}
),
}
)
# Extract and convert features
features = project_resources.get("features", [])
for feature in features:
results.append(
{
"type": "feature",
"name": feature.get("name", ""),
"description": feature.get("description", ""),
"project": current_project,
"featureView": feature.get("featureView", ""),
"tags": feature.get("tags", {}),
}
)
# Extract and convert feature services
feature_services = project_resources.get("featureServices", [])
for fs in feature_services:
results.append(
{
"type": "featureService",
"name": fs.get("featureService", {})
.get("spec", {})
.get("name", "")
or fs.get("spec", {}).get("name", ""),
"description": fs.get("featureService", {})
.get("spec", {})
.get("description", "")
or fs.get("spec", {}).get("description", ""),
"project": current_project,
"tags": fs.get("featureService", {})
.get("spec", {})
.get("tags", {})
or fs.get("spec", {}).get("tags", {}),
}
)
# Extract and convert saved datasets
saved_datasets = project_resources.get("savedDatasets", [])
for sd in saved_datasets:
results.append(
{
"type": "savedDataset",
"name": sd.get("savedDataset", {})
.get("spec", {})
.get("name", "")
or sd.get("spec", {}).get("name", ""),
"description": sd.get("savedDataset", {})
.get("spec", {})
.get("description", "")
or sd.get("spec", {}).get("description", ""),
"project": current_project,
"tags": sd.get("savedDataset", {})
.get("spec", {})
.get("tags", {})
or sd.get("spec", {}).get("tags", {}),
}
)
except Exception as e:
err_msg = f"Error getting resources for project '{current_project}'"
logger.error(f"{err_msg}: {e}")
errors.append(err_msg)
continue
# Apply search filtering
filtered_results = filter_search_results_and_match_score(results, query)
# Paginate & sort results
paginated_results, pagination = paginate_and_sort(
items=filtered_results,
page=pagination_params["page"],
limit=pagination_params["limit"],
sort_by=sorting_params["sort_by"],
sort_order=sorting_params["sort_order"],
)
# Remove tags from results before returning to user
cleaned_result = _remove_tags_from_results(paginated_results)
response = {
"query": query,
"projects_searched": projects_to_search,
"results": cleaned_result,
"pagination": pagination,
"errors": errors,
}
return response
return router
def _validate_projects(
input_projects: Optional[List[str]], grpc_handler, allow_cache: bool
) -> tuple[List[str], str]:
"""Validate projects and return list of existing projects"""
projects_to_search = []
nonexistent_projects = []
err_msg = ""
# Handling case of empty projects parameter i.e. /search?query=user&projects=
if input_projects is None:
input_projects = []
input_projects = [p for p in input_projects if p and p.strip()]
try:
all_projects, _, err_msg = list_all_projects(
grpc_handler=grpc_handler,
allow_cache=allow_cache,
)
if all_projects == []:
err_msg = "No projects found"
else:
project_names = {
proj.get("spec", {}).get("name", "")
for proj in all_projects
if proj.get("spec", {}).get("name")
}
if input_projects:
for project in input_projects:
if project in project_names:
projects_to_search.append(project)
else:
nonexistent_projects.append(project)
else:
projects_to_search = list(project_names)
if nonexistent_projects:
err_msg = f"Following projects do not exist: {', '.join(nonexistent_projects)}"
logger.error(f"{err_msg}")
except Exception as e:
err_msg = "Error getting projects"
logger.error(f"{err_msg}: {e}")
finally:
return list(set(projects_to_search)), err_msg
def _remove_tags_from_results(results: List[Dict]) -> List[Dict]:
"""Remove tags field from search results before returning to user"""
cleaned_results = []
for result in results:
# Create a copy without the tags field
cleaned_result = {k: v for k, v in result.items() if k != "tags"}
cleaned_results.append(cleaned_result)
return cleaned_results