add single endpoint for stats (section 1)

This commit is contained in:
Steven Tischer
2026-07-19 16:51:27 +02:00
parent 129142dfba
commit aead21ceb2
3 changed files with 176 additions and 1 deletions
+133
View File
@@ -16,6 +16,7 @@ from .. import config
from .model import (
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorTopicStats,
AuthorYearlyWorks,
CareerStage,
CompanyStatusFilter,
@@ -466,6 +467,138 @@ async def impact_stats_for_authors(
return results
def _topic_stats_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds a single query with all stats for Section 1"""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": filters,
},
},
"aggs": {
"authors": {
"nested": {"path": "authorships"},
"aggs": {
"selected": {
"filter": {"terms": {"authorships.author.id": author_ids}},
"aggs": {
"by_author": {
"terms": {
"field": "authorships.author.id",
"size": len(author_ids),
"execution_hint": "map",
},
"aggs": {
"author_name": {
"terms": {
"field": "authorships.author.display_name.keyword",
"size": 1,
"execution_hint": "map",
},
},
"corresponding": {
"filter": {
"term": {"authorships.is_corresponding": True},
},
},
"to_work": {
"reverse_nested": {},
"aggs": {
"avg_percentile": {
"avg": {
"field": "citation_normalized_percentile.value",
},
},
"top1": {
"filter": {
"term": {
"citation_normalized_percentile.is_in_top_1_percent": True,
},
},
},
"top10": {
"filter": {
"term": {
"citation_normalized_percentile.is_in_top_10_percent": True,
},
},
},
},
},
},
},
},
},
},
},
},
}
async def topic_stats_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> List[AuthorTopicStats]:
if not author_ids:
return []
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_topic_stats_query(author_ids, keywords, operator, publication_types, timespan),
cluster=ESCluster.NES,
)
author_buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("selected", {})
.get("by_author", {})
.get("buckets", [])
)
results = []
for author_bucket in author_buckets:
to_work = author_bucket.get("to_work", {})
avg_value = to_work.get("avg_percentile", {}).get("value")
results.append(
AuthorTopicStats(
author_id=author_bucket.get("key", ""),
display_name=_display_name_from_bucket(author_bucket),
works_total=author_bucket.get("doc_count", 0),
corresponding_count=author_bucket.get("corresponding", {}).get("doc_count", 0),
avg_percentile=float(avg_value) if avg_value is not None else 0.0,
top1_count=to_work.get("top1", {}).get("doc_count", 0),
top10_count=to_work.get("top10", {}).get("doc_count", 0),
)
)
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 = []
+22
View File
@@ -202,6 +202,28 @@ class AuthorImpactStats(BaseModel):
)
class AuthorTopicStats(BaseModel):
"""Section 1: combined stats over an author's works that match the topic filter."""
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
works_total: int = Field(
description="Number of the author's works matching the topic filter.",
)
corresponding_count: int = Field(
description="Number of the author's topic works where they are the corresponding author.",
)
avg_percentile: float = Field(
description="Average field-normalized citation percentile (0-1) over the author's topic works.",
)
top1_count: int = Field(
description="Number of the author's topic works in the top 1% most-cited.",
)
top10_count: int = Field(
description="Number of the author's topic works in the top 10% most-cited.",
)
class RankedAuthor(BaseModel):
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
+21 -1
View File
@@ -8,6 +8,7 @@ from . import logic
from .model import (
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorTopicStats,
AuthorYearlyWorks,
KeywordToAuthorRequest,
RankedAuthor,
@@ -21,7 +22,7 @@ router = APIRouter(
tags=[Tags.RANKING],
)
# Author ranking
@router.post("/rank-author", response_model=List[RankedAuthor])
async def rank_author(request: KeywordToAuthorRequest):
logger.info(
@@ -45,6 +46,25 @@ async def rank_author(request: KeywordToAuthorRequest):
request.company_status,
)
# Compare authors table 1 (topic stats)
@router.post("/topic-stats", response_model=List[AuthorTopicStats])
async def topic_stats(request: SelectedAuthorsRequest):
logger.info(
"topic-stats author_ids=%s keywords=%s operator=%s publication_types=%s timespan=%s",
request.author_ids,
request.keywords,
request.operator,
request.publication_types,
request.timespan,
)
return await logic.topic_stats_for_authors(
request.author_ids,
request.keywords,
request.operator,
request.publication_types,
request.timespan,
)
@router.post("/rank-selected-author", response_model=List[AuthorYearlyWorks])
async def rank_selected_author(request: SelectedAuthorsRequest):