11"""Database logic."""
2+ import asyncio
23import logging
34from base64 import urlsafe_b64decode , urlsafe_b64encode
45from typing import Dict , List , Optional , Tuple , Type , Union
@@ -196,24 +197,28 @@ async def execute_search(
196197 base_url : str ,
197198 ) -> Tuple [List [Item ], Optional [int ], Optional [str ]]:
198199 """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-
205200 search_after = None
206201 if token :
207202 search_after = urlsafe_b64decode (token .encode ()).decode ().split ("," )
208203
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 ))
215218 )
216219
220+ es_response = await search_task
221+
217222 hits = es_response ["hits" ]["hits" ]
218223 items = [
219224 self .item_serializer .db_to_stac (hit ["_source" ], base_url = base_url )
@@ -226,6 +231,15 @@ async def execute_search(
226231 "," .join ([str (x ) for x in sort_array ]).encode ()
227232 ).decode ()
228233
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+
229243 return items , maybe_count , next_token
230244
231245 """ TRANSACTION LOGIC """
0 commit comments