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 | @router.post("/api/v1/search")
async def search(req: SearchQueryRequest):
"""
Search datasets using hybrid keyword and semantic vector search.
Combines BM25 full-text matching against `title` and `description` with
k-NN vector search using sentence embeddings. Supports optional filtering
by source domain, dataset type, temporal range, and spatial bounding box.
Args:
req (SearchQueryRequest): Query parameters including:
- `keywords`: optional free-text to match and vectorize
- `source`: optional list or single source/domain
- `types`: optional list or single type
- `temporal_start` / `temporal_end`: ISO date strings to filter temporal coverage
- `bbox`: bounding box [min_lon, min_lat, max_lon, max_lat]
- `limit`: number of results to return
- `offset`: pagination offset
Returns:
A dict with:
- `total`: total number of matching datasets.
- `results`: list of dataset source documents (plot fields stripped).
- `aggregations`: facet counts for `sources_count` and `types_count`
Raises:
HTTPException: If required backends or dependencies are missing or an
error occurs while querying the search backend.
"""
try:
client = get_client()
except RuntimeError as exc:
raise HTTPException(status_code=500, detail=str(exc))
filter_clauses = []
should_clauses = []
query_vector = None
if req.keywords:
query_vector = build_query_vector(req.keywords)
if isinstance(req.source, list):
source_values = [item for item in req.source if item]
if source_values:
filter_clauses.append({"terms": {"domain": source_values}})
elif req.source:
filter_clauses.append({"term": {"domain": {"value": req.source}}})
if isinstance(req.types, list):
type_values = [item for item in req.types if item]
if type_values:
filter_clauses.append({"terms": {"types": type_values}})
elif req.types:
filter_clauses.append({"term": {"types": {"value": req.types}}})
# Temporal overlap: ensure dataset window overlaps requested window
if req.temporal_start:
# dataset.end >= temporal_start
filter_clauses.append({"range": {"temporal_coverage.end": {"gte": req.temporal_start}}})
if req.temporal_end:
# dataset.start <= temporal_end
filter_clauses.append({"range": {"temporal_coverage.start": {"lte": req.temporal_end}}})
if req.bbox:
try:
min_lon, min_lat, max_lon, max_lat = req.bbox
except Exception:
raise HTTPException(status_code=400, detail="Invalid bbox format; expected [min_lon, min_lat, max_lon, max_lat]")
envelope = [[min_lon, max_lat], [max_lon, min_lat]]
filter_clauses.append(
{
"geo_shape": {
"spatial_coverage.bbox": {
"shape": {"type": "envelope", "coordinates": envelope},
"relation": "intersects",
}
}
}
)
if req.keywords:
try:
description_fields = description_fields_for(req.description_source)
except ValueError as exc:
# A typo'd source must not silently fall back to the default arm.
raise HTTPException(status_code=400, detail=str(exc))
should_clauses.append(
{
"multi_match": {
"query": req.keywords,
"fields": description_fields,
}
}
)
should_clauses.append(
{
"knn": {
"dataset_vector": {
"vector": query_vector,
"k": 10,
}
}
}
)
query_bool = {"filter": filter_clauses}
if should_clauses:
query_bool["should"] = should_clauses
query_bool["minimum_should_match"] = 1 # Require at least one text or vector match when keywords are present
payload = {
"query": {"bool": query_bool},
"aggs": {
"sources_count": {"terms": {"field": "domain"}},
"types_count": {"terms": {"field": "types"}},
},
}
# print("RAW OPENSEARCH PAYLOAD:", json.dumps(payload, indent=2))
try:
resp = client.search(index="auctus_catalog_master", body=payload, size=req.limit, from_=req.offset)
except Exception as exc:
raise HTTPException(status_code=503, detail=f"Search backend error: {exc}")
hits = resp.get("hits", {}).get("hits", [])
total = resp.get("hits", {}).get("total")
if isinstance(total, dict):
total_count = total.get("value", 0)
else:
total_count = int(total or 0)
results = []
for h in hits:
src = h.get("_source", {})
# Remove large plot objects from profiler_metadata.columns
prof = src.get("profiler_metadata")
if isinstance(prof, dict):
cols = prof.get("columns")
if isinstance(cols, list):
for c in cols:
if isinstance(c, dict) and "plot" in c:
c.pop("plot", None)
results.append(src)
aggregations = resp.get("aggregations", {})
return {"total": total_count, "results": results, "aggregations": aggregations}
|