feat(work-classifications): optimized aggregation retrieval, moved chart to own component, and added chart for institution publications
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Mats Paul Tončik
2026-07-20 21:11:17 +02:00
parent 9da17840ad
commit a5664e01fe
29 changed files with 980 additions and 667 deletions
@@ -47,6 +47,21 @@ async def search_authors(
return AuthorPage(elements=authors, total=len(authors), page=page, size=size)
async def get_author_by_id(author_id: str) -> Optional[Author]:
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
Args:
author_id (str): The ID of the author to retrieve.
Returns:
Optional[Author]: The retrieved author, or None if not found.
"""
response = await elasticsearch.get(index=ESIndex.OPENALEX_AUTHORS, doc_id=author_id)
if not response.get("found"):
return None
return Author.from_dict(response.get("_source", {})) # type: ignore
async def autocomplete_authors_for_selector(query: str) -> AuthorPage:
"""Autocompletes authors based on a search term for use in a selector component.
@@ -95,3 +110,36 @@ async def get_authors_by_ids(author_ids: List[str]) -> AuthorPage:
"works_count",
],
)
async def author_currently_belongs_to_institution(
raw_oa_author_id: str,
raw_oa_institution_id: str,
current_years: List[int] = [2025, 2026],
) -> bool:
"""Checks if an author currently belongs to a specific institution based on their affiliations and the provided years.
Args:
raw_oa_author_id (str): The ID of the author to check.
raw_oa_institution_id (str): The ID of the institution to check.
current_years (List[int], optional): The years to check for affiliation. Defaults to [2025, 2026].
Returns:
bool: True if the author belongs to the institution in any of the specified years, False otherwise.
"""
author = await get_author_by_id(raw_oa_author_id)
if not author:
return False
for affiliation in author.affiliations or []:
institution = affiliation.institution
if not institution:
continue
if institution.id == f"https://openalex.org/{raw_oa_institution_id}" and any(
year in (affiliation.years or []) for year in current_years
):
return True
return False
@@ -129,6 +129,7 @@ async def search(
size: Optional[int] = None,
offset: Optional[int] = None,
sort: Optional[List] = None,
aggs: Optional[Dict] = None,
body: Optional[Dict] = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
@@ -143,6 +144,7 @@ async def search(
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
offset (Optional[int], optional): The number of results to skip. Defaults to None.
sort (Optional[List], optional): The fields to sort by. Defaults to None.
aggs (Optional[Dict], optional): The aggregations to include in the response. Defaults to None.
body (Optional[Dict], optional): The full query body. Defaults to None.
track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False.
cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES.
@@ -189,6 +191,8 @@ async def search(
payload["from"] = offset
if sort is not None:
payload["sort"] = sort
if aggs is not None:
payload["aggs"] = aggs
if track_total_hits:
payload["track_total_hits"] = True
if highlight is not None:
@@ -196,7 +200,7 @@ async def search(
if len(payload) == 0:
raise ValueError(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
)
client = get_client()
+7 -6
View File
@@ -1,6 +1,6 @@
from datetime import datetime
from enum import StrEnum
from typing import Optional, List
from typing import Dict, Optional, List
from pydantic import BaseModel, Field
@@ -179,12 +179,13 @@ class WorkClassificationPage(Page[WorkClassification]):
pass
class WorkClassificationMerge(BaseModel):
work: Work = Field(description="The OpenAlex work object.")
classification: Optional[WorkClassification] = Field(
default=None, description="The classification result for the work."
class PrimaryCategoryYearAggregation(BaseModel):
publication_year: int = Field(description="The publication year.")
categories: Dict[WorkPrimaryCategory, int] = Field(
default_factory=dict,
description="A mapping of primary categories to their counts for the given year.",
)
class WorkClassificationMergePage(Page[WorkClassificationMerge]):
class PrimaryCategoryYearAggregationPage(Page[PrimaryCategoryYearAggregation]):
pass
+120 -55
View File
@@ -6,15 +6,16 @@ from fastapi import APIRouter, Path, Query
from inse.tags import Tags
from inse.model import SortDirection
from inse.works.v2.model import (
PrimaryCategoryYearAggregationPage,
WorkClassification,
WorkClassificationMergePage,
WorkClassificationPage,
WorkPageV2,
WorkSortBy,
)
from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.works.v2.service import get_works_by_keywords
import inse.works.v2.service as works_service
WORKS_v2_PREFIX = "/api/v2/works"
logger = logging.getLogger(__name__)
@@ -67,9 +68,7 @@ async def get_author_works(
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> WorkPageV2:
from inse.works.v2.service import get_author_works
return await get_author_works(
return await works_service.get_author_works(
raw_oa_author_id=raw_oa_author_id,
page=page,
size=size,
@@ -83,33 +82,65 @@ async def get_author_works(
sort_order=sort_order,
)
@router.get(
"/keyword/search",
operation_id="getWorksByKeywords",
response_model=WorkPageV2,
summary="Search works by topics or raw keywords with filters."
summary="Search works by topics or raw keywords with filters.",
)
async def search_works_by_keywords(
topics: Annotated[list[str] | None, Query(description="List of topics to match.")] = None,
topic_ids: Annotated[list[str] | None, Query(description="List of topic IDs to match.")] = None,
topics: Annotated[
list[str] | None, Query(description="List of topics to match.")
] = None,
topic_ids: Annotated[
list[str] | None, Query(description="List of topic IDs to match.")
] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(description="Additional topic IDs to filter results by, independent of search mode."),
Query(
description="Additional topic IDs to filter results by, independent of search mode."
),
] = None,
keywords: Annotated[list[str] | None, Query(description="Raw keywords to search in title/abstract.")] = None,
fuzzy: Annotated[bool, Query(description="Use topic resolution if True, otherwise use raw keywords.")] = True,
publication_year: Annotated[list[int] | None, Query(description="A list of publication years to filter by.")] = None,
publication_type: Annotated[list[str] | None, Query(description="A list of publication types to filter by.")] = None,
institution_ids: Annotated[list[str] | None, Query(description="A list of institution IDs to filter by.")] = None,
author_ids: Annotated[list[str] | None, Query(description="A list of author IDs to filter by.")] = None,
language: Annotated[list[str] | None, Query(description="A list of language codes to filter by.")] = None,
title: Annotated[str | None, Query(description="Title to search for in works.")] = None,
page: Annotated[int, Query(description="The page number to retrieve. (0-based)", ge=0)] = 0,
size: Annotated[int, Query(description="The number of works to retrieve per page.", ge=1, le=100)] = 10,
sort_by: Annotated[WorkSortBy, Query(description="The field to sort by.")] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[SortDirection, Query(description="The order to sort by.")] = SortDirection.DESCENDING,
keywords: Annotated[
list[str] | None, Query(description="Raw keywords to search in title/abstract.")
] = None,
fuzzy: Annotated[
bool,
Query(description="Use topic resolution if True, otherwise use raw keywords."),
] = True,
publication_year: Annotated[
list[int] | None, Query(description="A list of publication years to filter by.")
] = None,
publication_type: Annotated[
list[str] | None, Query(description="A list of publication types to filter by.")
] = None,
institution_ids: Annotated[
list[str] | None, Query(description="A list of institution IDs to filter by.")
] = None,
author_ids: Annotated[
list[str] | None, Query(description="A list of author IDs to filter by.")
] = None,
language: Annotated[
list[str] | None, Query(description="A list of language codes to filter by.")
] = None,
title: Annotated[
str | None, Query(description="Title to search for in works.")
] = None,
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> WorkPageV2:
return await get_works_by_keywords(
return await works_service.get_works_by_keywords(
topics=topics or [],
keywords=keywords or [],
fuzzy=fuzzy,
@@ -126,7 +157,8 @@ async def search_works_by_keywords(
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/institution/{raw_oa_institution_id}",
operation_id="getInstitutionWorkPage",
@@ -173,9 +205,7 @@ async def get_institution_works(
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> WorkPageV2:
from inse.works.v2.service import get_institution_works
return await get_institution_works(
return await works_service.get_institution_works(
raw_oa_institution_id=raw_oa_institution_id,
page=page,
size=size,
@@ -190,24 +220,6 @@ async def get_institution_works(
)
@router.get(
"/classification/author/{raw_oa_author_id}",
operation_id="getWorkClassificationsByAuthorId",
summary="Returns the classifications of an author's works based on their ID.",
)
async def get_work_classifications_by_author_id(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
) -> WorkClassificationMergePage:
from inse.works.v2.service import get_work_classifications_by_author_id
return await get_work_classifications_by_author_id(
access_token_metadata=access_token_metadata, raw_oa_author_id=raw_oa_author_id
)
@router.get(
"/classification/work/{raw_oa_work_id}",
operation_id="getWorkClassificationByWorkId",
@@ -219,9 +231,7 @@ async def get_work_classification_by_work_id(
],
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
) -> WorkClassification | None:
from inse.works.v2.service import get_work_classification_by_work_id
return await get_work_classification_by_work_id(
return await works_service.get_work_classification_by_work_id(
access_token_metadata=access_token_metadata, raw_oa_work_id=raw_oa_work_id
)
@@ -253,15 +263,70 @@ async def get_work_classifications_by_work_ids(
),
] = 10,
) -> WorkClassificationPage:
from inse.works.v2.service import get_work_classifications_by_work_ids
logger.debug(
f"Fetching work classifications for work IDs: {work_ids}, page: {page}, size: {size}"
)
return await get_work_classifications_by_work_ids(
return await works_service.get_work_classifications_by_work_ids(
access_token_metadata=access_token_metadata,
work_ids=work_ids or [],
page=page,
size=size,
)
@router.get(
"/institution/{raw_oa_institution_id}/primary-category-aggregations",
operation_id="getPrimaryCategoryAggregationsByInstitutionId",
summary="Returns the primary category aggregations of works for a given institution based on their ID.",
)
async def get_primary_category_aggregations_by_institution_id(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
raw_oa_institution_id: Annotated[
str, Path(description="The raw OpenAlex institution id.")
],
year_size: Annotated[
int,
Query(description="The number of years to retrieve aggregations for.", ge=1),
] = 100,
category_size: Annotated[
int,
Query(
description="The number of categories to retrieve aggregations for.", ge=1
),
] = 50,
) -> PrimaryCategoryYearAggregationPage:
return await works_service.get_primary_category_aggregations_by_institution_id(
access_token_metadata=access_token_metadata,
raw_oa_institution_id=raw_oa_institution_id,
year_size=year_size,
category_size=category_size,
)
@router.get(
"/author/{raw_oa_author_id}/primary-category-aggregations",
operation_id="getPrimaryCategoryAggregationsByAuthorId",
summary="Returns the primary category aggregations of works for a given author based on their ID",
)
async def get_primary_category_aggregations_by_author_id(
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
year_size: Annotated[
int,
Query(description="The number of years to retrieve aggregations for.", ge=1),
] = 100,
category_size: Annotated[
int,
Query(
description="The number of categories to retrieve aggregations for.", ge=1
),
] = 50,
) -> PrimaryCategoryYearAggregationPage:
return await works_service.get_primary_category_aggregations_by_author_id(
access_token_metadata=access_token_metadata,
raw_oa_author_id=raw_oa_author_id,
year_size=year_size,
category_size=category_size,
)
+197 -129
View File
@@ -4,15 +4,17 @@ from fastapi import Query
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection, ESCluster
from inse.works.v2.model import (
PrimaryCategoryYearAggregation,
PrimaryCategoryYearAggregationPage,
WorkClassification,
WorkClassificationPage,
WorkClassificationMerge,
WorkClassificationMergePage,
WorkPageV2,
WorkSortBy,
)
from inse.models.openalex.work import Work
from inse.auth.model import AccessTokenMetadata
import inse.authors.v2.service as author_service
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@@ -229,17 +231,24 @@ async def get_works(
return await _execute_works_search(must, page, size, sort_by, sort_order)
async def get_works_by_keywords(
topics: Optional[List[str]] = Query(None, description="List of topics to match."),
topic_ids: Optional[List[str]] = Query(None, description="List of topic IDs to match."),
topic_ids: Optional[List[str]] = Query(
None, description="List of topic IDs to match."
),
filter_topic_ids: Optional[List[str]] = Query(
None,
description="Additional topic IDs to filter results by (OR semantics), "
"applied independently of the fuzzy/keyword search mode.",
"applied independently of the fuzzy/keyword search mode.",
),
keywords: Optional[List[str]] = Query(
None, description="Raw keywords to search in title/abstract."
),
keywords: Optional[List[str]] = Query(None, description="Raw keywords to search in title/abstract."),
title: Optional[str] = None,
fuzzy: bool = Query(True, description="Use topic resolution if True, otherwise use raw keywords."),
fuzzy: bool = Query(
True, description="Use topic resolution if True, otherwise use raw keywords."
),
publication_year: Optional[List[int]] = Query(None),
publication_type: Optional[List[str]] = Query(None, alias="type"),
language: Optional[List[str]] = Query(None),
@@ -250,7 +259,7 @@ async def get_works_by_keywords(
sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR),
sort_order: SortDirection = Query(SortDirection.DESCENDING),
) -> WorkPageV2:
#print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}")
# print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}")
def _topics_nested_clause(should_clauses: List[Dict]) -> Dict:
return {
"nested": {
@@ -286,32 +295,50 @@ async def get_works_by_keywords(
elif keywords:
keyword_clauses = []
for kw in keywords:
keyword_clauses.append({
"bool": {
"should": [
{"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw}}}},
{"match_phrase": {"primary_topic.display_name": kw}},
{"match_phrase": {"title": kw}},
{"match_phrase": {"abstract": kw}},
_topics_nested_clause([
{"match_phrase": {"topics.display_name": kw}},
{"match_phrase": {"topics.field.display_name": kw}},
{"match_phrase": {"topics.subfield.display_name": kw}},
{"match_phrase": {"topics.domain.display_name": kw}},
]),
],
"minimum_should_match": 1,
keyword_clauses.append(
{
"bool": {
"should": [
{
"nested": {
"path": "keywords",
"query": {
"match_phrase": {"keywords.display_name": kw}
},
}
},
{"match_phrase": {"primary_topic.display_name": kw}},
{"match_phrase": {"title": kw}},
{"match_phrase": {"abstract": kw}},
_topics_nested_clause(
[
{"match_phrase": {"topics.display_name": kw}},
{"match_phrase": {"topics.field.display_name": kw}},
{
"match_phrase": {
"topics.subfield.display_name": kw
}
},
{
"match_phrase": {
"topics.domain.display_name": kw
}
},
]
),
],
"minimum_should_match": 1,
}
}
})
)
topic_clause = {"bool": {"must": keyword_clauses}}
if not topic_clause:
return WorkPageV2(elements=[], total=0, page=page, size=size)
#filters
# filters
must = [topic_clause]
if title:
must.append(_title_query(title))
if publication_year:
@@ -325,13 +352,13 @@ async def get_works_by_keywords(
if author_ids:
must.append(_authors_nested_query(author_ids))
#sorting
# sorting
if sort_by == WorkSortBy.TITLE:
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
print(f"Final query:",must)
#search
print(f"Final query:", must)
# search
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=[
@@ -359,7 +386,7 @@ async def get_works_by_keywords(
)
print(f"Elasticsearch response: {response}")
logger.debug(f"Query: {{'bool': {{'must': {must}}}}}")
#model mapping
# model mapping
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
hits = hits_block.get("hits", [])
@@ -375,6 +402,7 @@ async def get_works_by_keywords(
return WorkPageV2(elements=elements, total=total, page=page, size=size)
async def get_author_works(
raw_oa_author_id: str,
page: int,
@@ -469,80 +497,6 @@ async def get_institution_works(
)
async def get_work_classifications_by_author_id(
access_token_metadata: AccessTokenMetadata, raw_oa_author_id: str
) -> WorkClassificationMergePage:
"""Retrieves work classifications for a specific author, filtered by the effective institution ID from the access token metadata.
Args:
access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID.
raw_oa_author_id (str): The ID of the author for whom to retrieve work classifications.
Returns:
WorkClassificationMergePage: The page of work classifications matching the criteria.
"""
raw_account_institution_id = access_token_metadata.effective_institution_id
work_page = await _get_work_ids_with_publication_year_for_author_id(
raw_oa_author_id=raw_oa_author_id
)
logger.debug(
f"Fetched {len(work_page.elements)} works for author {raw_oa_author_id} with publication year and institution {raw_account_institution_id}"
)
works_dict: Dict[str, Work] = {
work.id: work
for work in work_page.elements
if work.id is not None and work.publication_year is not None
}
work_ids = list(works_dict.keys())
logger.debug(
f"Filtered to {len(work_ids)} works for author {raw_oa_author_id} with publication year and institution {raw_account_institution_id}"
)
allowed_work_ids: List[str] = []
for work in works_dict.values():
if work.id and _work_has_authorship_with_institution_id(
work, raw_account_institution_id
):
allowed_work_ids.append(work.id)
logger.debug(
f"Filtered to {len(allowed_work_ids)} works for author {raw_oa_author_id} that are associated with institution {raw_account_institution_id}"
)
# all works considered here are associated with the account institution, so we can fetch their classifications without further filtering
work_classification_page = await _get_work_classifications_by_work_ids(
work_ids=allowed_work_ids, page=0, size=len(allowed_work_ids)
)
works_classifications_dict: Dict[str, WorkClassification] = {
work.work_id: work for work in work_classification_page.elements
}
logger.debug(
f"Fetched {len(works_classifications_dict)} work classifications for author {raw_oa_author_id} and institution {raw_account_institution_id}"
)
work_classification_merges: List[WorkClassificationMerge] = [
WorkClassificationMerge(
work=works_dict[work_id],
classification=works_classifications_dict.get(
work_id, None
), # None, if no classification exists for this work -> work is from another institution, or has not been classified yet
)
for work_id in work_ids
]
logger.debug(
f"Created {len(work_classification_merges)} work classification merges for author {raw_oa_author_id} and institution {raw_account_institution_id}"
)
return WorkClassificationMergePage(
elements=work_classification_merges,
total=len(work_classification_merges),
page=0,
size=len(work_classification_merges),
)
async def get_work(
raw_oa_work_id: str, source: Optional[List[str]] = None
) -> Work | None:
@@ -556,6 +510,7 @@ async def get_work(
Work | None: The retrieved work, or None if not found.
"""
# search instead of get, because multiple indices are used for works
work_page = await search_works(
query={"term": {"id": _prefix_id(raw_oa_work_id)}},
source=source,
@@ -607,32 +562,6 @@ async def search_works(
return WorkPageV2(elements=works, total=total, page=page, size=size)
async def _get_work_ids_with_publication_year_for_author_id(
raw_oa_author_id: str,
) -> WorkPageV2:
"""Retrieves works for a specific author, including only those works that have a publication year and are associated with the specified author ID.
Args:
raw_oa_author_id (str): The ID of the author for which to retrieve works.
Returns:
WorkPageV2: The page of works matching the criteria.
"""
return await search_works(
query={
"nested": {
"path": "authorships",
"query": {
"term": {"authorships.author.id": _prefix_id(raw_oa_author_id)}
},
}
},
source=["id", "publication_year", "authorships.institutions.id"],
size=10000,
)
async def _get_works_by_work_ids_and_institution_id(
work_ids: List[str], raw_oa_institution_id: str | None
) -> WorkPageV2:
@@ -889,3 +818,142 @@ def _prefix_id(raw_id: str) -> str:
if not raw_id.startswith("https://openalex.org/"):
return f"https://openalex.org/{raw_id}"
return raw_id
async def _get_primary_category_year_aggregations(
nested_path: str,
term_field: str,
term_value: str,
year_size: int = 100,
category_size: int = 50,
) -> PrimaryCategoryYearAggregationPage:
"""Gets primary category aggregations by year for works that match a specific term in a nested field.
Args:
nested_path (str): The path to the nested field in the Elasticsearch index.
term_field (str): The field within the nested path to filter by.
term_value (str): The value to filter the term field by.
year_size (int, optional): The maximum number of years to include in the aggregation. Defaults to 100.
category_size (int, optional): The maximum number of categories to include in the aggregation. Defaults to 50.
Returns:
PrimaryCategoryYearAggregationPage: A page of primary category aggregations by year for the matching works.
"""
response = await elasticsearch.search(
ESIndex.WORK_CLASSIFICATIONS,
query={
"nested": {
"path": nested_path,
"query": {"term": {term_field: term_value}},
}
},
size=0,
aggs={
"by_year": {
"terms": {
"field": "publication_year",
"size": year_size,
"order": {"_key": "asc"},
},
"aggs": {
"by_category": {
"terms": {
"field": "classification.primary_category",
"size": category_size,
}
}
},
}
},
)
year_buckets = (
response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
)
results: List[PrimaryCategoryYearAggregation] = []
for year_bucket in year_buckets:
category_buckets = year_bucket.get("by_category", {}).get("buckets", [])
categories = {cb["key"]: cb["doc_count"] for cb in category_buckets}
results.append(
PrimaryCategoryYearAggregation(
publication_year=year_bucket["key"],
categories=categories,
)
)
return PrimaryCategoryYearAggregationPage(
elements=results, total=len(results), page=0, size=len(results)
)
async def get_primary_category_aggregations_by_institution_id(
access_token_metadata: AccessTokenMetadata,
raw_oa_institution_id: str,
year_size: int = 100,
category_size: int = 50,
) -> PrimaryCategoryYearAggregationPage:
"""Gets primary category aggregations by year for works associated with a specific institution ID, filtered by the effective institution ID from the access token metadata.
Args:
access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID.
raw_oa_institution_id (str): The raw OpenAlex institution ID.
year_size (int, optional): The maximum number of years to include in the aggregation. Defaults to 100.
category_size (int, optional): The maximum number of categories to include in the aggregation. Defaults to 50.
Returns:
PrimaryCategoryYearAggregationPage: A page of primary category aggregations by year for the matching works.
"""
account_raw_oa_institution_id = access_token_metadata.effective_institution_id
if account_raw_oa_institution_id != raw_oa_institution_id:
return PrimaryCategoryYearAggregationPage(elements=[])
prefixed_institution_id = _prefix_id(raw_oa_institution_id)
return await _get_primary_category_year_aggregations(
nested_path="institutions",
term_field="institutions.id",
term_value=prefixed_institution_id,
year_size=year_size,
category_size=category_size,
)
async def get_primary_category_aggregations_by_author_id(
access_token_metadata: AccessTokenMetadata,
raw_oa_author_id: str,
year_size: int = 100,
category_size: int = 50,
) -> PrimaryCategoryYearAggregationPage:
"""Gets primary category aggregations by year for works associated with a specific author ID, filtered by the effective institution ID from the access token metadata.
Args:
access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID.
raw_oa_author_id (str): The raw OpenAlex author ID.
year_size (int, optional): The maximum number of years to include in the aggregation. Defaults to 100.
category_size (int, optional): The maximum number of categories to include in the aggregation. Defaults to 50.
Returns:
PrimaryCategoryYearAggregationPage: A page of primary category aggregations by year for the matching works.
"""
account_institution_id = access_token_metadata.effective_institution_id
if not account_institution_id:
return PrimaryCategoryYearAggregationPage(elements=[])
if not await author_service.author_currently_belongs_to_institution(
raw_oa_author_id, account_institution_id
):
return PrimaryCategoryYearAggregationPage(elements=[])
prefixed_author_id = _prefix_id(raw_oa_author_id)
return await _get_primary_category_year_aggregations(
nested_path="authors",
term_field="authors.id",
term_value=prefixed_author_id,
year_size=year_size,
category_size=category_size,
)