From a948182da5be9f32af0a8a20ac8d8f24ffbd9c97 Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 20 Jul 2026 01:16:56 +0200 Subject: [PATCH] added backed endpoints for DFG persons and institutions filters --- service/src/main/inse/main.py | 4 + .../inse/projects/dfg_institutions/model.py | 8 + .../inse/projects/dfg_institutions/router.py | 47 ++++ .../inse/projects/dfg_institutions/service.py | 200 ++++++++++++++ .../main/inse/projects/dfg_persons/model.py | 8 + .../main/inse/projects/dfg_persons/router.py | 47 ++++ .../main/inse/projects/dfg_persons/service.py | 244 ++++++++++++++++++ service/src/main/inse/tags.py | 3 + webapp/src/app/app.routes.ts | 10 +- 9 files changed, 567 insertions(+), 4 deletions(-) create mode 100644 service/src/main/inse/projects/dfg_institutions/model.py create mode 100644 service/src/main/inse/projects/dfg_institutions/router.py create mode 100644 service/src/main/inse/projects/dfg_institutions/service.py create mode 100644 service/src/main/inse/projects/dfg_persons/model.py create mode 100644 service/src/main/inse/projects/dfg_persons/router.py create mode 100644 service/src/main/inse/projects/dfg_persons/service.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 1fa1b997..083faa6d 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -58,6 +58,8 @@ from inse.authors.v2.router import router as authors_v2_router from inse.institutions.v2.router import router as institutions_v2_router from inse.topics.v2.router import router as topics_v2_router +from inse.projects.dfg_institutions.router import router as dfg_institutions_router +from inse.projects.dfg_persons.router import router as dfg_persons_router logger = logging.getLogger(__name__) ### startup @@ -112,6 +114,8 @@ app.include_router(institutions_v2_router) app.include_router(topics_v2_router) app.include_router(dashboard_router) +app.include_router(dfg_institutions_router) +app.include_router(dfg_persons_router) app.include_router(bookmarks_router) app.add_middleware( diff --git a/service/src/main/inse/projects/dfg_institutions/model.py b/service/src/main/inse/projects/dfg_institutions/model.py new file mode 100644 index 00000000..32f18aec --- /dev/null +++ b/service/src/main/inse/projects/dfg_institutions/model.py @@ -0,0 +1,8 @@ +from inse.model import Page +#from inse.models.projects_dfg_v2.institute.dfg_institute import DFGInstitute +from inse.projects.model import DfgInstitutionSummary + +class DfgInstitutionSummaryPage(Page[DfgInstitutionSummary]): + """A paginated response containing a list of institutions.""" + + pass diff --git a/service/src/main/inse/projects/dfg_institutions/router.py b/service/src/main/inse/projects/dfg_institutions/router.py new file mode 100644 index 00000000..a3e74631 --- /dev/null +++ b/service/src/main/inse/projects/dfg_institutions/router.py @@ -0,0 +1,47 @@ +import logging +from typing import Annotated + +from fastapi import APIRouter, Query + +from inse.projects.dfg_institutions.model import DfgInstitutionSummaryPage +from inse.tags import Tags +from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_ids + +logger = logging.getLogger(__name__) + + +INSTITUTIONS_DFG_PREFIX = "/api/dfg/institutions" + +router = APIRouter(prefix=INSTITUTIONS_DFG_PREFIX, tags=[Tags.DFG_INSTITUTIONS]) + + +@router.get( + "/ids", + operation_id="getDfgInstitutionsByIds", + summary="Returns a list of institutions based on their IDs.", +) +async def get_dfg_institutions( + institution_ids: Annotated[ + list[str], + Query(description="A list of institution IDs to retrieve."), + ] = [], +) -> DfgInstitutionSummaryPage: + + return await get_institutions_by_ids(institution_ids=institution_ids or []) + + +@router.get( + "/autocomplete/selector", + operation_id="getDfgInstitutionAutocompleteForSelector", + summary="Returns a list of institutions based on a search term for autocomplete functionality.", +) +async def get_dfg_institution_autocomplete( + query: Annotated[ + str, + Query( + description="A search term to filter institutions by (partial matches allowed)." + ), + ] = "", +) -> DfgInstitutionSummaryPage: + + return await autocomplete_institutions_for_selector(query=query) diff --git a/service/src/main/inse/projects/dfg_institutions/service.py b/service/src/main/inse/projects/dfg_institutions/service.py new file mode 100644 index 00000000..aeb1f5e4 --- /dev/null +++ b/service/src/main/inse/projects/dfg_institutions/service.py @@ -0,0 +1,200 @@ +import logging +from typing import Dict, List, Optional + +from inse.integrations import elasticsearch +from inse.model import ESIndex, ESCluster +#from inse.models.projects_dfg_v2.institute.dfg_institute import DFGInstitute +from inse.projects.model import DfgInstitutionSummary +from inse.projects.dfg_institutions.model import DfgInstitutionSummaryPage + +logger = logging.getLogger(__name__) + + +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, +) -> DfgInstitutionSummaryPage: + """Searches for institutions in the DFG Institutes Elasticsearch index based on the provided parameters. + + 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: + DfgInstitutionSummaryPage: A page of institutions matching the search criteria. + """ + response = await elasticsearch.search( + index=ESIndex.PROJECTS_DFG_INSTITUTES, + cluster=ESCluster.INSE, + query=query, + source=source, + size=size, + offset=size * page, + sort=sort, + body=body, + ) + + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + institutions: List[DfgInstitutionSummary] = [] + for hit in hits: + _source = hit.get("_source", {}) + # Handle nested institute object if present + if "institute" in _source and isinstance(_source["institute"], dict): + # Merge institute fields into top-level if needed + institute_data = _source.pop("institute") + _source.update(institute_data) + institutions.append(DfgInstitutionSummary(**_source)) # type: ignore + + return DfgInstitutionSummaryPage( + elements=institutions, + total=hits_block.get("total", {}).get("value", len(institutions)), + page=page, + size=size, + ) + + +async def get_institutions_by_ids(institution_ids: List[str]) -> DfgInstitutionSummaryPage: + """Retrieves institutions based on a list of institution IDs. + + Args: + institution_ids (List[str]): A list of institution IDs to retrieve. + + Returns: + DfgInstitutionSummaryPage: A page of institutions matching the provided IDs. + """ + logger.debug(f"Fetching institutions for IDs: {institution_ids}") + if not institution_ids: + return DfgInstitutionSummaryPage(elements=[], total=0, page=0, size=0) + + return await search_institutions( + page=0, + size=len(institution_ids), + query={ + "terms": { + "id": institution_ids + } + }, + source=[ + "id", + "institute_name_de", + "institute_name_en", + "address_country_de", + "address_country_en", + "address_street", + "root_id", + "root_name_de", + "root_name_en", + ], + ) + + +async def autocomplete_institutions( + query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None +) -> DfgInstitutionSummaryPage: + """Autocompletes institutions based on a search term. + + 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: + DfgInstitutionSummaryPage: A page of institutions matching the autocomplete criteria. + """ + logger.debug(f"Autocomplete institutions for query: {query}") + if not query: + return DfgInstitutionSummaryPage(elements=[], total=0, page=0, size=0) + + return await search_institutions( + page=page, + size=size, + query={ + "bool": { + "should": [ + { + "match_phrase_prefix": { + "institute_name_de": { + "query": query, + "max_expansions": 50, + } + } + }, + { + "match_phrase_prefix": { + "institute_name_en": { + "query": query, + "max_expansions": 50, + } + } + }, + { + "match_phrase_prefix": { + "root_name_de": { + "query": query, + "max_expansions": 50, + } + } + }, + { + "match_phrase_prefix": { + "root_name_en": { + "query": query, + "max_expansions": 50, + } + } + }, + ], + "minimum_should_match": 1, + } + }, + source=source or [ + "id", + "institute_name_de", + "institute_name_en", + "root_id", + "root_name_de", + "root_name_en", + "address_country_de", + "address_country_en", + ], + ) + + +async def autocomplete_institutions_for_selector( + query: str, page: int = 0, size: int = 10 +) -> DfgInstitutionSummaryPage: + """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: + DfgInstitutionSummaryPage: A page of institutions matching the autocomplete criteria. + """ + return await autocomplete_institutions( + query=query, + page=page, + size=size, + source=[ + "id", + "institute_name_de", + "institute_name_en", + "root_id", + "root_name_de", + "root_name_en", + "address_country_de", + "address_country_en", + ], + ) \ No newline at end of file diff --git a/service/src/main/inse/projects/dfg_persons/model.py b/service/src/main/inse/projects/dfg_persons/model.py new file mode 100644 index 00000000..1acf1c6e --- /dev/null +++ b/service/src/main/inse/projects/dfg_persons/model.py @@ -0,0 +1,8 @@ +from inse.model import Page +#from inse.models.projects_dfg_v2.institute.dfg_institute import DFGInstitute +from inse.projects.model import DfgPersonSummary + +class DfgPersonSummaryPage(Page[DfgPersonSummary]): + """A paginated response containing a list of persons.""" + + pass diff --git a/service/src/main/inse/projects/dfg_persons/router.py b/service/src/main/inse/projects/dfg_persons/router.py new file mode 100644 index 00000000..a3f6f18f --- /dev/null +++ b/service/src/main/inse/projects/dfg_persons/router.py @@ -0,0 +1,47 @@ +import logging +from typing import Annotated + +from fastapi import APIRouter, Query + +from inse.projects.dfg_persons.model import DfgPersonSummaryPage +from inse.tags import Tags +from inse.projects.dfg_persons.service import autocomplete_persons_for_selector, get_persons_by_ids + +logger = logging.getLogger(__name__) + + +INSTITUTIONS_DFG_PREFIX = "/api/dfg/persons" + +router = APIRouter(prefix=INSTITUTIONS_DFG_PREFIX, tags=[Tags.DFG_PERSONS]) + + +@router.get( + "/ids", + operation_id="getDfgPersonsByIds", + summary="Returns a list of persons based on their IDs.", +) +async def get_dfg_persons_by_ids( + person_ids: Annotated[ + list[str], + Query(description="A list of person IDs to retrieve."), + ] = [], +) -> DfgPersonSummaryPage: + + return await get_persons_by_ids(person_ids=person_ids or []) + + +@router.get( + "/autocomplete/selector", + operation_id="getDfgPersonAutocompleteForSelector", + summary="Returns a list of persons based on a search term for autocomplete functionality.", +) +async def get_dfg_person_autocomplete( + query: Annotated[ + str, + Query( + description="A search term to filter persons by (partial matches allowed)." + ), + ] = "", +) -> DfgPersonSummaryPage: + + return await autocomplete_persons_for_selector(query=query) diff --git a/service/src/main/inse/projects/dfg_persons/service.py b/service/src/main/inse/projects/dfg_persons/service.py new file mode 100644 index 00000000..9685add4 --- /dev/null +++ b/service/src/main/inse/projects/dfg_persons/service.py @@ -0,0 +1,244 @@ +import logging +from typing import Dict, List, Optional + +from inse.integrations import elasticsearch +from inse.model import ESIndex, ESCluster +from inse.projects.model import DfgPersonSummary, DfgInstitutionSummary +from inse.projects.dfg_persons.model import DfgPersonSummaryPage + +logger = logging.getLogger(__name__) + + +async def search_persons( + page: int = 0, + size: int = 10, + query: Optional[Dict] = None, + source: Optional[List[str]] = None, + sort: Optional[List[Dict]] = None, + body: Optional[Dict] = None, +) -> DfgPersonSummaryPage: + """Searches for persons in the DFG Persons Elasticsearch index. + + Args: + page (int, optional): Page number. Defaults to 0. + size (int, optional): Number of results per page. Defaults to 10. + query (Optional[Dict], optional): Elasticsearch query DSL. Defaults to None. + source (Optional[List[str]], optional): Fields to include in response. Defaults to None. + sort (Optional[List[Dict]], optional): Sorting criteria. Defaults to None. + body (Optional[Dict], optional): Full request body. Defaults to None. + + Returns: + DfgPersonSummaryPage: Paginated list of persons. + """ + print(query) + response = await elasticsearch.search( + index=ESIndex.PROJECTS_DFG_PERSONS, + cluster=ESCluster.INSE, + query=query, + source=source, + size=size, + offset=size * page, + sort=sort, + body=body, + ) + + hits_block = response.get("hits", {}) + hits = hits_block.get("hits", []) + persons: List[DfgPersonSummary] = [] + + for hit in hits: + _source = hit.get("_source", {}) + + # Merge top-level person data with nested `person` object + if "person" in _source and isinstance(_source["person"], dict): + person_data = _source.pop("person") + _source.update(person_data) + + # Extract person-level fields + person_id = _source.get("person_id") or _source.get("id") + full_name = _source.get("full_name") + + institution = None + + if "institute_id" in _source and _source.get("institute_id") is not None: + institution = DfgInstitutionSummary( + institute_name_de=_source.get("institute_name_de"), + institute_name_en=_source.get("institute_name_en"), + root_name_de=_source.get("root_name_de"), + root_name_en=_source.get("root_name_en"), + root_id=_source.get("root_id"), + id=_source.get("institute_id"), + ) + + # Extract projects (only first 10 or relevant ones) + projects = [] + if "projects" in _source and isinstance(_source["projects"], list): + for proj in _source["projects"][:size]: # Limit to avoid bloat + projects.append( + DfgPersonSummary( + person_id=person_id, + project_ref_id=proj.get("project_id"), + full_name=full_name, + role_label_en=proj.get("role_label_en"), + role_label_de=proj.get("role_label_de"), + institution=institution, + ) + ) + + # If no projects, still create a summary + if not projects: + projects.append( + DfgPersonSummary( + person_id=person_id, + project_ref_id=None, + full_name=full_name, + role_label_en=None, + role_label_de=None, + institution=institution, + ) + ) + + # Add all project summaries + persons.extend(projects) + + return DfgPersonSummaryPage( + elements=persons, + total=hits_block.get("total", {}).get("value", len(persons)), + page=page, + size=size, + ) + + +async def get_persons_by_ids(person_ids: List[str]) -> DfgPersonSummaryPage: + """Retrieves persons by their IDs. + + Args: + person_ids (List[str]): List of person IDs (as strings). + + Returns: + DfgPersonSummaryPage: Page of persons matching the IDs. + """ + logger.debug(f"Fetching persons for IDs: {person_ids}") + if not person_ids: + return DfgPersonSummaryPage(elements=[], total=0, page=0, size=0) + + return await search_persons( + page=0, + size=len(person_ids), + query={ + "terms": { + "id": person_ids # or "person_id", depending on index mapping + } + }, + source=[ + "id", + "person_id", + "full_name", + "orcid_id", + "is_deceased", + "institute_name_de", + "institute_name_en", + "institute_id", + "root_name_de", + "root_name_en", + "root_id", + ], + ) + + +async def autocomplete_persons( + query: str, + page: int = 0, + size: int = 10, + source: Optional[List[str]] = None, +) -> DfgPersonSummaryPage: + """Autocomplete persons based on full name or ORCID. + + Args: + query (str): Search term. + page (int, optional): Page number. Defaults to 0. + size (int, optional): Results per page. Defaults to 10. + source (Optional[List[str]], optional): Fields to include. Defaults to None. + + Returns: + DfgPersonSummaryPage: Matching persons. + """ + logger.debug(f"Autocomplete persons for query: {query}") + if not query: + return DfgPersonSummaryPage(elements=[], total=0, page=0, size=0) + + return await search_persons( + page=page, + size=size, + query={ + "bool": { + "should": [ + { + "match_phrase_prefix": { + "full_name": { + "query": query, + "max_expansions": 50, + "analyzer": "searchabilityAnalyzer" + } + } + }, + { + "match_phrase_prefix": { + "orcid_id": { + "query": query, + "max_expansions": 50 + } + } + }, + ], + "minimum_should_match": 1, + } + }, + source=source or [ + "id", + "person_id", + "full_name", + "orcid_id", + "institute_name_de", + "institute_name_en", + "institute_id", + "root_name_de", + "root_name_en", + "root_id", + "projects", + ], + ) + + +async def autocomplete_persons_for_selector( + query: str, + page: int = 0, + size: int = 10, +) -> DfgPersonSummaryPage: + """Autocomplete persons for use in a selector UI component. + + Args: + query (str): Search term. + page (int, optional): Page number. Defaults to 0. + size (int, optional): Results per page. Defaults to 10. + + Returns: + DfgPersonSummaryPage: Matching persons with minimal fields. + """ + return await autocomplete_persons( + query=query, + page=page, + size=size, + source=[ + "id", + "person_id", + "full_name", + "orcid_id", + "institute_name_de", + "institute_name_en", + "institute_id", + "root_name_de", + "root_name_en", + "root_id", + ], + ) \ No newline at end of file diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py index 5eb73000..3a7eefcc 100644 --- a/service/src/main/inse/tags.py +++ b/service/src/main/inse/tags.py @@ -19,3 +19,6 @@ class Tags(StrEnum): INSTITUTIONS_V2 = "Institutions V2" TOPICS_V2 = "Topics V2" WORKS_V2 = "Works V2" + + DFG_INSTITUTIONS = "DFG Institutions" + DFG_PERSONS = "DFG Persons" diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 459f5e12..5368cc05 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -41,6 +41,8 @@ import { personCordisEuProjectPageResolver } from './resolvers/person-cordis-eu- import { selectedAuthorsResolver } from './resolvers/selected-authors.resolver'; import { authorWorkClassificationPageResolver } from './resolvers/author-work-classification-page.resolver'; import { workClassificationResolver } from './resolvers/work-classification.resolver'; +import { selectedDfgAuthorsResolver } from './resolvers/selected-dfg-authors.resolver'; +import { selectedDfgInstitutionsResolver } from './resolvers/selected-dfg-institutions.resolver'; export const routes: Routes = [ { path: '', @@ -380,10 +382,10 @@ export const routes: Routes = [ resolve: { dfgProjectPage: dfgProjectsResolver, personCordisEuProjectPage: personCordisEuProjectPageResolver, - selectedDfgInstitutions: selectedInstitutionsResolver, - selectedDfgAuthors: selectedAuthorsResolver, - selectedEuInstitutions: selectedInstitutionsResolver, - selectedEuAuthors: selectedAuthorsResolver, + selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver, + selectedDfgAuthorsPage: selectedDfgAuthorsResolver, + selectedEuInstitutionsPage: selectedInstitutionsResolver, + selectedEuAuthorsPage: selectedAuthorsResolver, }, runGuardsAndResolvers: 'always', },