Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve: Add count function to async resource service #2739

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions superdesk/core/resources/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
Loading