From 57e1bafa8bb982048cdf7c1a1ba2ed0f62044689 Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 28 Jul 2026 00:30:20 +0200 Subject: [PATCH] added BUND institutions endpoint with autocomplete --- service/src/main/inse/main.py | 2 + .../inse/projects/bund_institutions/model.py | 42 +++++ .../inse/projects/bund_institutions/router.py | 47 +++++ .../projects/bund_institutions/service.py | 169 ++++++++++++++++++ service/src/main/inse/projects/model.py | 11 +- service/src/main/inse/tags.py | 2 + 6 files changed, 271 insertions(+), 2 deletions(-) create mode 100644 service/src/main/inse/projects/bund_institutions/model.py create mode 100644 service/src/main/inse/projects/bund_institutions/router.py create mode 100644 service/src/main/inse/projects/bund_institutions/service.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 8318ac59..07750aed 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -52,6 +52,7 @@ from inse.patents.service import ( ) from inse.persons.service import router as persons_service_router from inse.projects.dfg_institutions.router import router as dfg_institutions_router +from inse.projects.bund_institutions.router import router as bund_institutions_router from inse.projects.dfg_persons.router import router as dfg_persons_router from inse.projects.eu_organizations.router import router as eu_organizations_router from inse.projects.router import router as projects_router @@ -103,6 +104,7 @@ app = FastAPI( app.include_router(institution_patents_router) app.include_router(org_patents_router) app.include_router(institutions_router) +app.include_router(bund_institutions_router) app.include_router(topics_service_router) app.include_router(works_service_router) app.include_router(persons_service_router) diff --git a/service/src/main/inse/projects/bund_institutions/model.py b/service/src/main/inse/projects/bund_institutions/model.py new file mode 100644 index 00000000..7a4099fe --- /dev/null +++ b/service/src/main/inse/projects/bund_institutions/model.py @@ -0,0 +1,42 @@ +from typing import Optional + +from inse.model import Page +from pydantic import BaseModel + + +class BundInstitutionSummary(BaseModel): + """A single institution entry derived from a BUND project record. + + Note: this index has no dedicated institution entity — each entry is + reconstructed from the agency/recipient fields on a single project hit, + so the same institution may appear multiple times (once per project). + """ + + department: Optional[str] = None + department_fullname: Optional[str] = None + name: Optional[str] = None + recepient: Optional[str] = None + municipality: Optional[str] = None + place: Optional[str] = None + state: Optional[str] = None + country: Optional[str] = None + + @classmethod + def from_source(cls, source: dict) -> "BundInstitutionSummary": + """Build a BundInstitutionSummary from a raw Elasticsearch _source dict.""" + return cls( + department=source.get("Ressort"), + department_fullname=source.get("Ressort_fullname"), + name=source.get("Ausführende Stelle"), + recepient=source.get("Zuwendungsempfänger"), + municipality=source.get("Stadt/Gemeinde"), + place=source.get("Ort"), + state=source.get("Bundesland"), + country=source.get("Staat"), + ) + + +class BundInstitutionSummaryPage(Page[BundInstitutionSummary]): + """A paginated response containing a list of institutions.""" + + pass \ No newline at end of file diff --git a/service/src/main/inse/projects/bund_institutions/router.py b/service/src/main/inse/projects/bund_institutions/router.py new file mode 100644 index 00000000..51c2ae68 --- /dev/null +++ b/service/src/main/inse/projects/bund_institutions/router.py @@ -0,0 +1,47 @@ +import logging +from typing import Annotated + +from fastapi import APIRouter, Query + +from inse.projects.bund_institutions.model import BundInstitutionSummaryPage +from inse.tags import Tags +from inse.projects.bund_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_names + +logger = logging.getLogger(__name__) + + +INSTITUTIONS_BUND_PREFIX = "/api/bund/institutions" + +router = APIRouter(prefix=INSTITUTIONS_BUND_PREFIX, tags=[Tags.BUND_INSTITUTIONS]) + + +@router.get( + "/names", + operation_id="getBundInstitutionsByName", + summary="Returns a list of institutions based on their names.", +) +async def get_bund_institutions( + institution_names: Annotated[ + list[str], + Query(description="A list of institution names to retrieve."), + ] = [], +) -> BundInstitutionSummaryPage: + + return await get_institutions_by_names(institution_names=institution_names or []) + + +@router.get( + "/autocomplete/selector", + operation_id="getBundInstitutionAutocompleteForSelector", + summary="Returns a list of institutions based on a search term for autocomplete functionality.", +) +async def get_bund_institution_autocomplete( + query: Annotated[ + str, + Query( + description="A search term to filter institutions by (partial matches allowed)." + ), + ] = "", +) -> BundInstitutionSummaryPage: + + return await autocomplete_institutions_for_selector(query=query) diff --git a/service/src/main/inse/projects/bund_institutions/service.py b/service/src/main/inse/projects/bund_institutions/service.py new file mode 100644 index 00000000..c550391e --- /dev/null +++ b/service/src/main/inse/projects/bund_institutions/service.py @@ -0,0 +1,169 @@ +import logging +from typing import Dict, List, Optional + +from inse.integrations import elasticsearch +from inse.model import ESIndex, ESCluster + +from inse.projects.bund_institutions.model import BundInstitutionSummary +from inse.projects.bund_institutions.model import BundInstitutionSummaryPage + +logger = logging.getLogger(__name__) + +# Fields on the BUND project index that describe the institution/agency involved, +# used consistently across all lookup functions below. +_INSTITUTION_SOURCE_FIELDS = [ + "Ressort", + "Ressort_fullname", + "Ausführende Stelle", + "Zuwendungsempfänger", + "Stadt/Gemeinde", + "Ort", + "Bundesland", + "Staat", +] + + +async def search_institutions( + page: int = 0, + size: int = 10, + query: Optional[Dict] = None, + source: Optional[List[str]] = None, + sort: Optional[List[Dict]] = None, + body: Optional[Dict] = None, +) -> BundInstitutionSummaryPage: + """Searches for institutions in the BUND Projects Elasticsearch index based on the provided parameters. + + Note: PROJECTS_BUND_V1 indexes projects, not institutions directly, so each + matching project hit is reshaped into a BundInstitutionSummary. The same + institution may therefore appear multiple times if it's tied to multiple projects. + + Args: + page (int, optional): The page number to retrieve. Defaults to 0. + size (int, optional): The number of institutions to retrieve per page. Defaults to 10. + query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None. + source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None. + sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None. + body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None. + + Returns: + BundInstitutionSummaryPage: A page of institutions matching the search criteria. + """ + response = await elasticsearch.search( + index=ESIndex.PROJECTS_BUND_V1, + cluster=ESCluster.INSE, + query=query, + source=source or _INSTITUTION_SOURCE_FIELDS, + size=size, + offset=size * page, + sort=sort, + body=body, + ) + + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + institutions: List[BundInstitutionSummary] = [ + BundInstitutionSummary.from_source(hit.get("_source", {})) for hit in hits + ] + + return BundInstitutionSummaryPage( + elements=institutions, + total=hits_block.get("total", {}).get("value", len(institutions)), + page=page, + size=size, + ) + + +async def get_institutions_by_names(institution_names: List[str]) -> BundInstitutionSummaryPage: + """Retrieves institutions based on a list of institution (Ausführende Stelle) names. + + Args: + institution_names (List[str]): A list of institution names to retrieve. + + Returns: + BundInstitutionSummaryPage: A page of institutions matching the provided names. + """ + logger.debug(f"Fetching institutions for names: {institution_names}") + if not institution_names: + return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0) + + return await search_institutions( + page=0, + size=len(institution_names), + query={ + "terms": { + "Ausführende Stelle.keyword": institution_names, + } + }, + source=_INSTITUTION_SOURCE_FIELDS, + ) + + +async def autocomplete_institutions( + query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None +) -> BundInstitutionSummaryPage: + """Autocompletes institutions based on a search term, matching against both the + executing agency (Ausführende Stelle) and recipient (Zuwendungsempfänger) fields. + + Args: + query (str): The search term to autocomplete institutions with. + page (int, optional): The page number to retrieve. Defaults to 0. + size (int, optional): The number of institutions to retrieve per page. Defaults to 10. + source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None. + + Returns: + BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria. + """ + logger.debug(f"Autocomplete institutions for query: {query}") + if not query: + return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0) + + return await search_institutions( + page=page, + size=size, + query={ + "bool": { + "should": [ + { + "match_phrase_prefix": { + "Ausführende Stelle": { + "query": query, + "max_expansions": 50, + "boost": 2, + } + } + }, + { + "match_phrase_prefix": { + "Zuwendungsempfänger": { + "query": query, + "max_expansions": 50, + } + } + }, + ], + "minimum_should_match": 1, + } + }, + source=source or _INSTITUTION_SOURCE_FIELDS, + ) + + +async def autocomplete_institutions_for_selector( + query: str, page: int = 0, size: int = 10 +) -> BundInstitutionSummaryPage: + """Autocompletes institutions based on a search term for use in a selector component. + + Args: + query (str): The search term to filter institutions by (partial matches allowed). + page (int, optional): The page number to retrieve. Defaults to 0. + size (int, optional): The number of institutions to retrieve per page. Defaults to 10. + + Returns: + BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria. + """ + return await autocomplete_institutions( + query=query, + page=page, + size=size, + source=_INSTITUTION_SOURCE_FIELDS, + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/model.py b/service/src/main/inse/projects/model.py index af12afd7..7094cba5 100644 --- a/service/src/main/inse/projects/model.py +++ b/service/src/main/inse/projects/model.py @@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDet from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield from inse.authors.v2.model import AuthorPage +from inse.projects.bund_institutions.model import BundInstitutionSummary from typing import Union class ProjectType(StrEnum): @@ -75,6 +76,11 @@ class BundProjectSummary(BundProject): description="The OpenAlex topics of the project", examples=[["Artificial Intelligence", "Machine Learning"]], ) + institution: Optional[BundInstitutionSummary] = Field( + default=None, + description="The executing agency / recipient institution for this project, " + "derived from the project's own agency fields.", + ) @classmethod def from_hit(cls, hit: dict) -> "BundProjectSummary": @@ -109,8 +115,8 @@ class BundProjectSummary(BundProject): topic=source.get("Thema"), performance_plan_system=source.get("Leistungsplansystematik"), performance_plan_system_text=source.get("Klartext Leistungsplansystematik"), - funding_start=source.get("Förderbeginn"), - funding_end=source.get("Förderende"), + funding_start=source.get("funding_start"), + funding_end=source.get("funding_end"), grant_amount=source.get("Fördersumme"), funding_profile=source.get("Förderprofil"), joint_project=source.get("Verbundprojekt"), @@ -121,6 +127,7 @@ class BundProjectSummary(BundProject): new=source.get("neu"), duration=source.get("Laufzeit"), oa_topics=oa_topics, + institution=BundInstitutionSummary.from_source(source), ) @staticmethod diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 3440bd2f..c3bf0f89 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -24,3 +24,5 @@ class Tags(StrEnum): DFG_INSTITUTIONS = "DFG Institutions" DFG_PERSONS = "DFG Persons" BACKGROUND_JOBS = "Background Jobs" + + BUND_INSTITUTIONS = "BUND Institutions"