From af4c0850e354f824f487f13b5ffdd3314f0c0d5f Mon Sep 17 00:00:00 2001 From: genja Date: Tue, 23 Jun 2026 21:48:38 +0200 Subject: [PATCH] index names strings replaced by ESIndex enum --- service/src/main/inse/model.py | 41 +- .../eu_cordis_projects_enrichment_client.py | 413 +++++++----------- 2 files changed, 197 insertions(+), 257 deletions(-) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index 98aaf28c..9633207b 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -56,9 +56,40 @@ class ESIndex(StrEnum): OPENALEX_INSTITUTIONS = "openalex-institutions" OPENALEX_PUBLICATIONS = "openalex-publications" - CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" - CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" - CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" - PROJECTS_BUND_V1 = "projects_bund_v1" - PROJECTS_DFG_ALL = "projects_dfg_all" \ No newline at end of file + PROJECTS_DFG_ALL = "projects_dfg_all" + + CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" + CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects" + CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications" + CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations" + # FP7 + CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations" + CORDIS_EU_FP7_PUBLICATIONS = "cordis_eu_fp7_publications" + CORDIS_EU_FP7_PROJECT_IPRS = "cordis_eu_fp7_project_iprs" + CORDIS_EU_FP7_REPORT_SUMMARIES = "cordis_eu_fp7_report_summaries" + CORDIS_EU_FP7_TOPICS = "cordis_eu_fp7_topics" + CORDIS_EU_FP7_WEB_LINKS = "cordis_eu_fp7_web_links" + CORDIS_EU_FP7_EUROSCIVOC = "cordis_eu_fp7_euroscivoc" + CORDIS_EU_FP7_LEGAL_BASIS = "cordis_eu_fp7_legal_basis" + + # Horizon 2020 + CORDIS_EU_HORIZON_2020_ORGANIZATIONS = "cordis_eu_horizon_2020_organizations" + CORDIS_EU_HORIZON_2020_PUBLICATIONS = "cordis_eu_horizon_2020_publications" + CORDIS_EU_HORIZON_2020_DELIVERABLES = "cordis_eu_horizon_2020_deliverables" + CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES = "cordis_eu_horizon_2020_report_summaries" + CORDIS_EU_HORIZON_2020_TOPICS = "cordis_eu_horizon_2020_topics" + CORDIS_EU_HORIZON_2020_WEB_LINKS = "cordis_eu_horizon_2020_web_links" + CORDIS_EU_HORIZON_2020_EUROSCIVOC = "cordis_eu_horizon_2020_euroscivoc" + CORDIS_EU_HORIZON_2020_LEGAL_BASIS = "cordis_eu_horizon_2020_legal_basis" + CORDIS_EU_HORIZON_2020_ERC_PIS = "cordis_eu_horizon_2020_erc_pis" + + # Horizon Europe + CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations" + CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications" + CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables" + CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries" + CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics" + CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links" + CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc" + CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis" \ No newline at end of file diff --git a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py index 7871e202..5caff70e 100644 --- a/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py +++ b/service/src/main/inse/projects/eu_cordis_projects_enrichment_client.py @@ -1,5 +1,5 @@ -import json import logging +from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional, Union from inse.config import get_settings @@ -50,72 +50,193 @@ settings = get_settings() logger = logging.getLogger(__name__) logger.setLevel(settings.logging_level) +# Entity config +_FP7_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, "model_class": Fp7Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_FP7_PUBLICATIONS, "model_class": Fp7Publication}, + {"key": "iprs", "index_pattern": ESIndex.CORDIS_EU_FP7_PROJECT_IPRS, "model_class": Fp7ProjectIPR}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_FP7_REPORT_SUMMARIES, "model_class": Fp7ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_FP7_TOPICS, "model_class": Fp7Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_FP7_WEB_LINKS, "model_class": Fp7WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_FP7_EUROSCIVOC, "model_class": Fp7EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_FP7_LEGAL_BASIS, "model_class": Fp7LegalBasis}, +] + +_H2020_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, "model_class": H2020Organization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_PUBLICATIONS, "model_class": H2020Publication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_DELIVERABLES, "model_class": H2020Deliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_REPORT_SUMMARIES, "model_class": H2020ReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_TOPICS, "model_class": H2020Topic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_WEB_LINKS, "model_class": H2020WebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_EUROSCIVOC, "model_class": H2020EurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_LEGAL_BASIS, "model_class": H2020LegalBasis}, + {"key": "erc_principal_investigators", "index_pattern": ESIndex.CORDIS_EU_HORIZON_2020_ERC_PIS, "model_class": H2020ErcPI}, +] + +_HEU_ENTITY_CONFIGS = [ + {"key": "organizations", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, "model_class": HEUOrganization}, + {"key": "publications", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS, "model_class": HEUPublication}, + {"key": "deliverables", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_DELIVERABLES, "model_class": HEUDeliverable}, + {"key": "report_summaries", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES, "model_class": HEUReportSummary}, + {"key": "topics_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_TOPICS, "model_class": HEUTopic}, + {"key": "web_links", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_WEB_LINKS, "model_class": HEUWebLink}, + {"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc}, + {"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis}, +] def get_enriched_cordis_project_by_id( project_id: str, ) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]: """ - Fetches and enriches a single Cordis EU project by its ID across all program types. - + Fetches and enriches a single Cordis EU project by its ID across all programme types. + Args: - project_id: The project ID to fetch - + project_id: The project ID to fetch. + Returns: - The enriched detailed project model, or None if not found + The enriched detailed project model, or None if not found. """ if not project_id: return None - - # Step 1: Search for the project across all indices + query = {"bool": {"filter": [{"term": {"id": project_id}}]}} - + response = elasticsearch.search( query=query, index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD, cluster=ESCluster.INSE, size=1, ) - + hits = response.get("hits", {}).get("hits", []) if not hits: logger.info(f"No project found with ID: {project_id}") return None - + hit = hits[0] index = hit.get("_index", "") source = hit.get("_source", {}) - - # Determine program type from index name + program_type = _determine_program_type_from_index(index) - - # Enrich and return the project based on program type - if program_type == "fp7": - return _enrich_fp7_project(project_id, source) - elif program_type == "h2020": - return _enrich_h2020_project(project_id, source) - elif program_type == "heu": - return _enrich_heu_project(project_id, source) - else: - # Unknown type, return base model - logger.warning(f"Unknown program type for index: {index}") + + enrichers = { + "fp7": _enrich_fp7_project, + "h2020": _enrich_h2020_project, + "heu": _enrich_heu_project, + } + + enricher = enrichers.get(program_type) + if enricher is None: + logger.warning(f"Unknown programme type for index: {index}") return CordisEuProject.model_validate(source) + return enricher(project_id, source) +# helpers def _determine_program_type_from_index(index: str) -> str: - """Determines the program type from the Elasticsearch index name.""" + """Determines the programme type from the Elasticsearch index name.""" index_lower = index.lower() if "fp7" in index_lower: return "fp7" - elif "horizon_2020" in index_lower: + if "horizon_2020" in index_lower: return "h2020" - elif "heu" in index_lower or "horizon_europe" in index_lower: + if "heu" in index_lower or "horizon_europe" in index_lower: return "heu" return "unknown" +def _fetch_related_entities_parallel( + project_id: str, + entity_configs: List[Dict[str, Any]], + max_workers: int = 8, +) -> Dict[str, List[Any]]: + """ + Fetches all related entity types for a project in parallel. + + Args: + project_id: The project ID to fetch entities for. + entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'. + max_workers: Maximum number of concurrent Elasticsearch requests. + + Returns: + Dictionary mapping each config 'key' to a list of validated entities. + """ + def _fetch_one(config: Dict[str, Any]): + entities = _fetch_related_entities( + project_ids=[project_id], + index_pattern=config["index_pattern"], + model_class=config["model_class"], + ) + return config["key"], entities.get(project_id, []) + + results: Dict[str, List[Any]] = {} + with ThreadPoolExecutor(max_workers=max_workers) as executor: + futures = {executor.submit(_fetch_one, cfg): cfg["key"] for cfg in entity_configs} + for future in as_completed(futures): + try: + key, data = future.result() + results[key] = data + except Exception as e: + key = futures[future] + logger.error(f"Parallel fetch failed for '{key}': {e}") + results[key] = [] + + return results + + +def _fetch_related_entities( + project_ids: List[str], + index_pattern: str, + model_class: Any, +) -> Dict[str, List[Any]]: + """ + Fetches and groups related entities from Elasticsearch by project ID. + + Args: + project_ids: List of project IDs to fetch entities for. + index_pattern: The index pattern to search (supports wildcards). + model_class: The Pydantic model class to validate against. + + Returns: + Dictionary mapping project IDs to lists of validated entities. + """ + query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} + + try: + response = elasticsearch.search( + query=query, + index=index_pattern, + cluster=ESCluster.INSE, + size=10000, + ) + except Exception as e: + logger.warning(f"Failed to fetch from {index_pattern}: {e}") + return {} + + grouped: Dict[str, List[Any]] = {} + + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + project_id = source.get("projectID") + + if not project_id: + continue + + grouped.setdefault(project_id, []) + + try: + entity = model_class.model_validate(source) + grouped[project_id].append(entity) + except Exception as e: + logger.warning(f"Failed to validate {model_class.__name__} for project {project_id}: {e}") + + return grouped + + def _enrich_fp7_project( project_id: str, - project_source: Dict[str, Any] + project_source: Dict[str, Any], ) -> Optional[Fp7ProjectDetails]: """Enriches a single FP7 project with all related data.""" try: @@ -123,66 +244,15 @@ def _enrich_fp7_project( except Exception as e: logger.error(f"Failed to validate FP7 project {project_id}: {e}") return None - - # Fetch all related data - organizations = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_organizations", - model_class=Fp7Organization - ) - publications = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_publications", - model_class=Fp7Publication - ) - iprs = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_project_iprs", - model_class=Fp7ProjectIPR - ) - report_summaries = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_report_summaries", - model_class=Fp7ReportSummary - ) - topics_list = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_topics", - model_class=Fp7Topic - ) - web_links = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_web_links", - model_class=Fp7WebLink - ) - eurosci_voc = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_euroscivoc", - model_class=Fp7EurosciVoc - ) - legal_basis_list = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_fp7_legal_basis", - model_class=Fp7LegalBasis - ) - - # Build and return enriched project - return Fp7ProjectDetails.from_project_with_relations( - project=project, - organizations=organizations.get(project_id, []), - publications=publications.get(project_id, []), - iprs=iprs.get(project_id, []), - report_summaries=report_summaries.get(project_id, []), - topics_list=topics_list.get(project_id, []), - web_links=web_links.get(project_id, []), - eurosci_voc=eurosci_voc.get(project_id, []), - legal_basis_list=legal_basis_list.get(project_id, []), - ) + + related = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS) + + return Fp7ProjectDetails.from_project_with_relations(project=project, **related) def _enrich_h2020_project( project_id: str, - project_source: Dict[str, Any] + project_source: Dict[str, Any], ) -> Optional[H2020ProjectDetails]: """Enriches a single H2020 project with all related data.""" try: @@ -190,72 +260,15 @@ def _enrich_h2020_project( except Exception as e: logger.error(f"Failed to validate H2020 project {project_id}: {e}") return None - - # Fetch all related data - organizations = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_organizations", - model_class=H2020Organization - ) - publications = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_publications", - model_class=H2020Publication - ) - deliverables = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_deliverables", - model_class=H2020Deliverable - ) - report_summaries = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_report_summaries", - model_class=H2020ReportSummary - ) - topics_list = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_topics", - model_class=H2020Topic - ) - web_links = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_web_links", - model_class=H2020WebLink - ) - eurosci_voc = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_euroscivoc", - model_class=H2020EurosciVoc - ) - legal_basis_list = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_legal_basis", - model_class=H2020LegalBasis - ) - erc_pis = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_2020_erc_pis", - model_class=H2020ErcPI - ) - - # Build and return enriched project - return H2020ProjectDetails.from_project_with_relations( - project=project, - organizations=organizations.get(project_id, []), - publications=publications.get(project_id, []), - deliverables=deliverables.get(project_id, []), - report_summaries=report_summaries.get(project_id, []), - topics_list=topics_list.get(project_id, []), - web_links=web_links.get(project_id, []), - eurosci_voc=eurosci_voc.get(project_id, []), - legal_basis_list=legal_basis_list.get(project_id, []), - erc_principal_investigators=erc_pis.get(project_id, []), - ) + + related = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS) + + return H2020ProjectDetails.from_project_with_relations(project=project, **related) def _enrich_heu_project( project_id: str, - project_source: Dict[str, Any] + project_source: Dict[str, Any], ) -> Optional[HEUProjectDetails]: """Enriches a single Horizon Europe project with all related data.""" try: @@ -263,111 +276,7 @@ def _enrich_heu_project( except Exception as e: logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}") return None - - # Fetch all related data - organizations = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_organizations", - model_class=HEUOrganization - ) - print("ORGS",organizations) - publications = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_publications", - model_class=HEUPublication - ) - deliverables = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_deliverables", - model_class=HEUDeliverable - ) - report_summaries = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_report_summaries", - model_class=HEUReportSummary - ) - topics_list = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_topics", - model_class=HEUTopic - ) - web_links = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_web_links", - model_class=HEUWebLink - ) - eurosci_voc = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_euroscivoc", - model_class=HEUEurosciVoc - ) - legal_basis_list = _fetch_related_entities( - project_ids=[project_id], - index_pattern="cordis_eu_horizon_europe_legal_basis", - model_class=HEULegalBasis - ) - - # Build and return enriched project - return HEUProjectDetails.from_project_with_relations( - project=project, - organizations=organizations.get(project_id, []), - publications=publications.get(project_id, []), - deliverables=deliverables.get(project_id, []), - report_summaries=report_summaries.get(project_id, []), - topics_list=topics_list.get(project_id, []), - web_links=web_links.get(project_id, []), - eurosci_voc=eurosci_voc.get(project_id, []), - legal_basis_list=legal_basis_list.get(project_id, []), - ) + related = _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS) -def _fetch_related_entities( - project_ids: List[str], - index_pattern: str, - model_class: Any -) -> Dict[str, List[Any]]: - """ - Fetches and groups related entities from Elasticsearch by project ID. - - Args: - project_ids: List of project IDs to fetch entities for - index_pattern: The index pattern to search (supports wildcards) - model_class: The Pydantic model class to validate against - - Returns: - Dictionary mapping project IDs to lists of entities - """ - query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}} - - try: - response = elasticsearch.search( - query=query, - index=index_pattern, - cluster=ESCluster.INSE, - size=10000 - ) - except Exception as e: - logger.warning(f"Failed to fetch from {index_pattern}: {e}") - return {} - - grouped = {} - hits = response.get("hits", {}).get("hits", []) - - for hit in hits: - source = hit.get("_source", {}) - project_id = source.get("projectID") - - if not project_id: - continue - - if project_id not in grouped: - grouped[project_id] = [] - - try: - entity = model_class.model_validate(source) - grouped[project_id].append(entity) - except Exception as e: - logger.warning(f"Failed to validate entity for project {project_id}: {e}") - continue - - return grouped \ No newline at end of file + return HEUProjectDetails.from_project_with_relations(project=project, **related) \ No newline at end of file