diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py index ddf63707..b1ec3310 100644 --- a/service/src/main/inse/works/logic.py +++ b/service/src/main/inse/works/logic.py @@ -5,6 +5,7 @@ Business logic for publication works. """ import logging +from time import time from typing import List import httpx @@ -14,6 +15,7 @@ from starlette.status import HTTP_502_BAD_GATEWAY from starlette.status import HTTP_404_NOT_FOUND from starlette.status import HTTP_503_SERVICE_UNAVAILABLE +from inse import config from inse.integrations import elasticsearch from inse.models.work import Work from inse.models.work_page import WorkPage @@ -100,34 +102,76 @@ async def get_primary_topic_counts( author_id: str, client: OpenAlexWorksSearchClient | None = None, ) -> List[TopicCount]: - works = await get_all_author_works(author_id, client=client) + topic_counts = _get_primary_topic_counts_from_es(author_id) - counts = {} + topic_ids = [item["id"] for item in topic_counts if item["id"]] + details = _get_topic_details(topic_ids) - for work in works.results or []: - primary_topic = work.primary_topic - if not primary_topic or not primary_topic.display_name: + result = [] + + for item in topic_counts: + info = details.get(item["id"], {}) + name = info.get("display_name") + if not name: continue - name = primary_topic.display_name - if name not in counts: - counts[name] = {"id": primary_topic.id, "name": name, "count": 0} - counts[name]["count"] += 1 - - items = sorted(counts.values(), key=lambda item: item["count"], reverse=True) - - topic_ids = [item["id"] for item in items if item["id"]] - descriptions = _get_topic_descriptions(topic_ids) - - return [ - TopicCount( - id=item["id"], - name=item["name"], - count=item["count"], - description=descriptions.get(item["id"]), + result.append( + TopicCount( + id=item["id"], + name=name, + count=item["count"], + description=info.get("description"), + ) ) - for item in items - ] + + return result + + +def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]: + + indexed_author_id = f"https://openalex.org/{author_id.strip()}" + + body = { + "size": 0, + "query": { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + {"term": {"authorships.author.id": indexed_author_id}}, + ], + }, + }, + }, + }, + "aggs": { + "primary_topics": { + "terms": {"field": "primary_topic.id", "size": 1000}, + }, + }, + } + + try: + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + except httpx.HTTPError as exc: + logger.exception("OpenAlex primary topic aggregation request failed.") + raise HTTPException( + status_code=HTTP_502_BAD_GATEWAY, + detail="OpenAlex works search request failed.", + ) from exc + + aggregations = response.get("aggregations", {}) + buckets = aggregations.get("primary_topics", {}).get("buckets", []) + + counts = [] + for bucket in buckets: + counts.append({"id": bucket["key"], "count": bucket["doc_count"]}) + + return counts async def get_work( @@ -156,7 +200,7 @@ async def get_work( return elements[0] -def _get_topic_descriptions(topic_ids: List[str]) -> dict[str, str]: +def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]: if not topic_ids: return {} @@ -164,22 +208,26 @@ def _get_topic_descriptions(topic_ids: List[str]) -> dict[str, str]: response = elasticsearch.search( index="openalex-topics", query={"terms": {"id": topic_ids}}, - source=["id", "description"], + source=["id", "display_name", "description"], size=len(topic_ids), ) except httpx.HTTPError: - logger.exception("Could not load topic descriptions from Elasticsearch.") + logger.exception("Could not load topic details from Elasticsearch.") return {} - descriptions = {} + details = {} for hit in response.get("hits", {}).get("hits", []): source = hit.get("_source", {}) topic_id = source.get("id") - description = source.get("description") - if topic_id and description: - descriptions[topic_id] = description + if not topic_id: + continue - return descriptions + details[topic_id] = { + "display_name": source.get("display_name"), + "description": source.get("description"), + } + + return details def _limit_works_by_complete_years( diff --git a/webapp/src/app/modules/person-interesting/person-interesting.component.html b/webapp/src/app/modules/person-interesting/person-interesting.component.html index 34c35799..92f4d52a 100644 --- a/webapp/src/app/modules/person-interesting/person-interesting.component.html +++ b/webapp/src/app/modules/person-interesting/person-interesting.component.html @@ -2,7 +2,10 @@