add filter timespan (include works from/to)
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Steven Tischer
2026-07-09 10:53:59 +02:00
parent 3b9436474e
commit ecd21ce0a9
3 changed files with 42 additions and 5 deletions
+21 -2
View File
@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
import logging
from typing import Any, List
from typing import Any, List, Optional
from inse.integrations import elasticsearch
from inse.model import ESCluster
@@ -14,6 +14,7 @@ from .model import (
PublicationType,
RankedAuthor,
RankingWeights,
Timespan,
)
logger = logging.getLogger(__name__)
@@ -86,12 +87,25 @@ def _publication_type_filter(publication_types: List[PublicationType]) -> dict:
return {"terms": {"type": type_values}}
def _timespan_filter(timespan: Timespan) -> dict:
"""Keeps only works whose publication year is within the timespan (inclusive)."""
return {
"range": {
"publication_year": {
"gte": timespan.from_year,
"lte": timespan.to_year,
},
},
}
def _build_query(
keywords: List[str],
operator: KeywordOperator,
uni_id: str,
weights: RankingWeights,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds the Elasticsearch query for ranking authors by keywords."""
score_script = (
@@ -104,6 +118,8 @@ def _build_query(
]
if publication_types:
work_filters.append(_publication_type_filter(publication_types))
if timespan is not None:
work_filters.append(_timespan_filter(timespan))
return {
"size": 0,
@@ -282,13 +298,16 @@ async def rank_authors_by_keywords(
weights: RankingWeights,
career_stages: List[CareerStage],
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> List[RankedAuthor]:
"""Ranks the university's authors by a weighted score over works and citations.
When career_stages is not empty, the ranked list is filtered down to
authors whose career stage is one of the given stages.
"""
query_body = _build_query(keywords, operator, uni_id, weights, publication_types)
query_body = _build_query(
keywords, operator, uni_id, weights, publication_types, timespan
)
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
+17 -2
View File
@@ -4,9 +4,9 @@
Data models for author ranking.
"""
from enum import StrEnum
from typing import List
from typing import List, Optional
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, Field, field_validator, model_validator
class KeywordOperator(StrEnum):
@@ -47,6 +47,17 @@ class PublicationType(StrEnum):
REPORT_COMPONENT = "report-component"
GRANT = "grant"
class Timespan(BaseModel):
from_year: int = Field(alias="from", description="Start year (inclusive).")
to_year: int = Field(alias="to", description="End year (inclusive).")
@model_validator(mode="after")
def check_order(self):
if self.from_year > self.to_year:
raise ValueError("timespan 'from' must not be greater than 'to'.")
return self
class RankingWeights(BaseModel):
citation: float = Field(
ge=0.0,
@@ -84,6 +95,10 @@ class KeywordToAuthorRequest(BaseModel):
default_factory=list,
description="Optional filter: only count works of these publication types. Empty = no filter.",
)
timespan: Optional[Timespan] = Field(
default=None,
description="Optional filter: only count works whose publication_year is within [from, to].",
)
@field_validator("operator", mode="before")
@classmethod
+4 -1
View File
@@ -18,12 +18,14 @@ router = APIRouter(
@router.post("/rank-author", response_model=List[RankedAuthor])
async def rank_author(request: KeywordToAuthorRequest):
logger.info(
"rank-author keywords=%s operator=%s uni_id=%s career_stages=%s publication_types=%s",
"rank-author keywords=%s operator=%s uni_id=%s career_stages=%s "
"publication_types=%s timespan=%s",
request.keywords,
request.operator,
request.uni_id,
request.career_stages,
request.publication_types,
request.timespan,
)
return await logic.rank_authors_by_keywords(
request.keywords,
@@ -32,4 +34,5 @@ async def rank_author(request: KeywordToAuthorRequest):
request.weights,
request.career_stages,
request.publication_types,
request.timespan,
)