From 64ccedf44da2eaf78f261398c27f0841fab817d7 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 12 Jul 2026 17:06:52 +0200 Subject: [PATCH] feat: implement yearly works query and endpoint for selected authors --- service/src/main/inse/ranking/logic.py | 106 ++++++++++++++++++++++++ service/src/main/inse/ranking/model.py | 34 ++++++++ service/src/main/inse/ranking/router.py | 22 ++++- 3 files changed, 161 insertions(+), 1 deletion(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 659ad447..464f7ea5 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -12,12 +12,14 @@ from inse.model import ESCluster from inse.persons.logic import _classify_career_stage from .. import config from .model import ( + AuthorYearlyWorks, CareerStage, KeywordOperator, PublicationType, RankedAuthor, RankingWeights, Timespan, + YearCount, ) logger = logging.getLogger(__name__) @@ -108,6 +110,110 @@ def _author_filter(author_ids: List[str]) -> dict: } +def _yearly_works_query( + author_ids: List[str], + keywords: List[str], + operator: KeywordOperator, +) -> dict: + """Builds a query that returns, per selected author, the year distribution of their topic works.""" + return { + "size": 0, + "query": { + "bool": { + "filter": [ + _build_keyword_query(keywords, operator), + _author_filter(author_ids), + ], + }, + }, + "aggs": { + "authors": { + "nested": {"path": "authorships"}, + "aggs": { + "selected": { + # keep only the authorships of the selected authors + "filter": {"terms": {"authorships.author.id": author_ids}}, + "aggs": { + "by_author": { + "terms": { + "field": "authorships.author.id", + "size": len(author_ids), + "execution_hint": "map", + }, + "aggs": { + "to_work": { + "reverse_nested": {}, + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 200, + "order": {"_key": "desc"}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + +async def yearly_works_for_authors( + author_ids: List[str], + keywords: List[str], + operator: KeywordOperator, +) -> List[AuthorYearlyWorks]: + """For each selected author, returns the per-year count of their works on the topic. + + Only years with at least one work are returned, newest year first. + """ + if not author_ids: + return [] + + response: dict[str, Any] = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=_yearly_works_query(author_ids, keywords, operator), + cluster=ESCluster.NES, + ) + + author_buckets = ( + response.get("aggregations", {}) + .get("authors", {}) + .get("selected", {}) + .get("by_author", {}) + .get("buckets", []) + ) + + results = [] + for author_bucket in author_buckets: + year_buckets = ( + author_bucket.get("to_work", {}) + .get("publication_years", {}) + .get("buckets", []) + ) + years = [] + for year_bucket in year_buckets: + years.append( + YearCount( + year=int(year_bucket.get("key")), + count=year_bucket.get("doc_count", 0), + ) + ) + results.append( + AuthorYearlyWorks( + author_id=author_bucket.get("key", ""), + years=years, + ) + ) + + return results + + def _publication_type_filter(publication_types: List[PublicationType]) -> dict: """Keeps only works whose type is one of the given publication types.""" type_values = [] diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index c36c46dc..6ceb7e34 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -108,6 +108,40 @@ class KeywordToAuthorRequest(BaseModel): return value +class SelectedAuthorsRequest(BaseModel): + author_ids: List[str] = Field( + min_length=1, + description="OpenAlex IDs of the authors to rank.", + ) + keywords: List[str] = Field( + min_length=1, + description="One or more keywords defining the topic.", + ) + operator: KeywordOperator = Field( + default=KeywordOperator.AND, + description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", + ) + + @field_validator("operator", mode="before") + @classmethod + def operator_case_insensitive(cls, value): + if isinstance(value, str): + return value.lower() + return value + + +class YearCount(BaseModel): + year: int = Field(description="Publication year.") + count: int = Field(description="Number of the author's works on the topic in that year.") + + +class AuthorYearlyWorks(BaseModel): + author_id: str = Field(description="The OpenAlex ID of the author.") + years: List[YearCount] = Field( + description="Per-year count of the author's works on the topic, newest year first.", + ) + + class RankedAuthor(BaseModel): author_id: str = Field(description="The OpenAlex ID of the author.") display_name: str = Field(description="The name of the author.") diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index f8731cb2..0371f441 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -5,7 +5,12 @@ from fastapi import APIRouter from inse.tags import Tags from . import logic -from .model import KeywordToAuthorRequest, RankedAuthor +from .model import ( + AuthorYearlyWorks, + KeywordToAuthorRequest, + RankedAuthor, + SelectedAuthorsRequest, +) logger = logging.getLogger(__name__) @@ -36,3 +41,18 @@ async def rank_author(request: KeywordToAuthorRequest): request.publication_types, request.timespan, ) + + +@router.post("/rank-selected-author", response_model=List[AuthorYearlyWorks]) +async def rank_selected_author(request: SelectedAuthorsRequest): + logger.info( + "rank-selected-author author_ids=%s keywords=%s operator=%s", + request.author_ids, + request.keywords, + request.operator, + ) + return await logic.yearly_works_for_authors( + request.author_ids, + request.keywords, + request.operator, + )