1
1
"""Database logic."""
2
+ import asyncio
2
3
import logging
3
4
from base64 import urlsafe_b64decode , urlsafe_b64encode
4
5
from typing import Dict , List , Optional , Tuple , Type , Union
@@ -196,24 +197,28 @@ async def execute_search(
196
197
base_url : str ,
197
198
) -> Tuple [List [Item ], Optional [int ], Optional [str ]]:
198
199
"""Database logic to execute search with limit."""
199
- body = search .to_dict ()
200
-
201
- maybe_count = (
202
- await self .client .count (index = ITEMS_INDEX , body = search .to_dict (count = True ))
203
- ).get ("count" )
204
-
205
200
search_after = None
206
201
if token :
207
202
search_after = urlsafe_b64decode (token .encode ()).decode ().split ("," )
208
203
209
- es_response = await self .client .search (
210
- index = ITEMS_INDEX ,
211
- query = body .get ("query" ),
212
- sort = sort or DEFAULT_SORT ,
213
- search_after = search_after ,
214
- size = limit ,
204
+ query = search .query .to_dict () if search .query else None
205
+
206
+ search_task = asyncio .create_task (
207
+ self .client .search (
208
+ index = ITEMS_INDEX ,
209
+ query = query ,
210
+ sort = sort or DEFAULT_SORT ,
211
+ search_after = search_after ,
212
+ size = limit ,
213
+ )
214
+ )
215
+
216
+ count_task = asyncio .create_task (
217
+ self .client .count (index = ITEMS_INDEX , body = search .to_dict (count = True ))
215
218
)
216
219
220
+ es_response = await search_task
221
+
217
222
hits = es_response ["hits" ]["hits" ]
218
223
items = [
219
224
self .item_serializer .db_to_stac (hit ["_source" ], base_url = base_url )
@@ -226,6 +231,15 @@ async def execute_search(
226
231
"," .join ([str (x ) for x in sort_array ]).encode ()
227
232
).decode ()
228
233
234
+ # (1) count should not block returning results, so don't wait for it to be done
235
+ # (2) don't cancel the task so that it will populate the ES cache for subsequent counts
236
+ maybe_count = None
237
+ if count_task .done ():
238
+ try :
239
+ maybe_count = count_task .result ().get ("count" )
240
+ except Exception as e : # type: ignore
241
+ logger .error (f"Count task failed: { e } " )
242
+
229
243
return items , maybe_count , next_token
230
244
231
245
""" TRANSACTION LOGIC """
0 commit comments