From 6112951ab07778d8bf14ff92b74f4200b24ae8d9 Mon Sep 17 00:00:00 2001 From: Mark Pittaway Date: Thu, 24 Oct 2024 17:16:19 +1100 Subject: [PATCH] improve: Add count function to async resource service --- superdesk/core/resources/service.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/superdesk/core/resources/service.py b/superdesk/core/resources/service.py index cb3754ed7..81469e2dc 100644 --- a/superdesk/core/resources/service.py +++ b/superdesk/core/resources/service.py @@ -547,6 +547,25 @@ async def find( return await self._mongo_find(search_request) + async def count(self, lookup: dict[str, Any] | None = None, use_mongo: bool = False) -> int: + """Get the number of items that match the lookup, or all items if lookup is not provided + + Will use Elasticsearch if configured for this resource and ``use_mongo == False``. + This will not perform a search, but use the item count feature of the underlying data store + + :param lookup: Dictionary to search + :param use_mongo: Force to use MongoDB instead of Elasticsearch + :return: The number of items that match the lookup + """ + + try: + if not use_mongo: + return await self.elastic.count(lookup) + except KeyError: + pass + + return await self.mongo_async.count_documents(lookup or {}) + async def _mongo_find( self, req: SearchRequest, versioned: bool = False ) -> MongoResourceCursorAsync[ResourceModelType]: