Added documentation for projects search client
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit

This commit is contained in:
Mats Paul Tončik
2026-06-21 15:50:54 +02:00
parent f3539e4210
commit a0477fcdb1
2 changed files with 382 additions and 264 deletions
@@ -96,51 +96,22 @@ DFG_PERSON_FIELDS: List[str] = [
"stellvertr. Sprecherinnen / stellvertr. Sprecher",
]
class ProjectsSearchClient:
def __init__(
self,
base_url: str,
index: str,
api_key: str,
):
self.base_url = base_url
self.index = index
self.api_key = api_key
self.headers = {
"Content-Type": "application/json",
"Authorization": f"ApiKey {self.api_key}",
}
async def make_search_request(
self, query: dict, index: Optional[str] = None
) -> dict:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{self.base_url}/{index or self.index}/_search",
json=query,
headers=self.headers,
)
try:
response.raise_for_status()
except httpx.HTTPStatusError as e:
logger.exception(
f"HTTP error occurred: {e.response.status_code} - {e.response.text}"
)
raise
return response.json()
# BUND
def search_bund_projects(
page: int,
size: int,
filter_properties: ProjectsFilteringProperties,
institution_names: List[str] = [],
topic: Optional[str] = None,
sort_by: ProjectsSortBy = ProjectsSortBy.TITLE,
sort_direction: SortDirection = SortDirection.ASC,
) -> BundProjectPage:
"""Searches for Bund projects based on the provided filtering properties and institution names.
Args:
filter_properties (ProjectsFilteringProperties): The properties to filter the projects by.
institution_names (List[str], optional): The names of the institutions to filter by. Defaults to [].
Returns:
BundProjectPage: The page of Bund projects that match the filtering criteria.
"""
must_clauses: List[Dict[str, Any]] = []
if len(institution_names) > 0:
@@ -163,12 +134,12 @@ def search_bund_projects(
}
)
if topic is not None and topic.strip() != "":
if filter_properties.query is not None and filter_properties.query.strip() != "":
must_clauses.append(
{
"match_phrase_prefix": {
"Thema": {
"query": topic,
"query": filter_properties.query,
"max_expansions": 50,
}
}
@@ -179,24 +150,40 @@ def search_bund_projects(
if must_clauses:
query = {"bool": {"must": must_clauses}}
sort = [{sort_by.to_bund_project_sort_field(): {"order": sort_direction.value}}]
sort = [
{
filter_properties.sort_by.to_bund_project_sort_field(): {
"order": filter_properties.sort_direction.value
}
}
]
response = elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=query,
sort=sort,
size=size,
offset=page * size,
size=filter_properties.size,
offset=filter_properties.page * filter_properties.size,
)
return _complete_response_to_bund_project_page(
response=response, page=page, size=size
response=response, page=filter_properties.page, size=filter_properties.size
)
def _complete_response_to_bund_project_page(
response: Dict[str, Any], page: int, size: int
) -> BundProjectPage:
"""Converts the raw Elasticsearch response into a BundProjectPage object.
Args:
response (Dict[str, Any]): The raw Elasticsearch response.
page (int): The page number.
size (int): The number of items per page.
Returns:
BundProjectPage: The converted BundProjectPage object.
"""
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
@@ -206,6 +193,14 @@ def _complete_response_to_bund_project_page(
def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
"""Fetches the details of a single Bund project based on its project ID.
Args:
project_id (str): The ID of the project to fetch.
Returns:
Optional[BundProjectDetails]: The details of the project if found, otherwise None.
"""
query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}
response = elasticsearch.search(
@@ -222,6 +217,264 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
return None
# EU
def get_eu_organization_project_contributions(
organization_names: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
"""Fetches the contributions of EU organizations to projects based on the provided organization names and filtering properties, and returns a paginated summary of the projects.
Args:
organization_names (List[str]): The list of organization names to fetch contributions for.
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the projects.
Returns:
EuOrganizationProjectSummaryPage: The paginated summary of the projects.
"""
# Pagination depending on sorting criteria
# For FUNDING_AMOUNT before on the organization project contributions
# For the rest after the contributions are known on the real projects
organization_project_contributions = get_eu_organization_contributions(
organization_names=organization_names,
)
total_projects, projects = get_eu_organization_projects(
project_contributions=list(organization_project_contributions.values()),
projects_filtering_properties=projects_filtering_properties,
)
elements: List[EuOrganizationProjectSummary] = _merge_project_data(
projects=projects, contributions=organization_project_contributions
)
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
elements.sort(
key=lambda x: x.ec_contribution or 0,
reverse=projects_filtering_properties.sort_direction == SortDirection.DESC,
)
start = projects_filtering_properties.page * projects_filtering_properties.size
end = start + projects_filtering_properties.size
elements = elements[start:end]
return EuOrganizationProjectSummaryPage(
elements=elements,
total=total_projects,
page=projects_filtering_properties.page,
size=projects_filtering_properties.size,
)
def get_eu_organization_contributions(
organization_names: List[str],
) -> Dict[str, EuOrganizationShort]:
"""Fetches the contributions of EU organizations to projects based on the provided organization names.
Args:
organization_names (List[str]): The list of organization names to fetch contributions for.
Returns:
Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions.
"""
source = ["projectID", "organisationID", "ecContribution"]
query = {
"terms": {
"name.keyword": [
name.upper() for name in organization_names if name.strip()
],
}
}
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
size=10000,
query=query,
)
logger.debug(
f"Received organization project contributions response: {json.dumps(response, indent=2)}"
)
organization_project_contributions = _process_organization_project_contributions(
response
)
logger.debug(
f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}"
)
return organization_project_contributions
def _process_organization_project_contributions(
response: Dict[str, Any],
) -> Dict[str, EuOrganizationShort]:
"""Processes the raw Elasticsearch response to extract the contributions of EU organizations to projects.
Args:
response (Dict[str, Any]): The raw Elasticsearch response.
Returns:
Dict[str, EuOrganizationShort]: A dictionary mapping project IDs to their corresponding organization contributions.
"""
hits_block = response.get("hits", {})
project_contributions: Dict[str, EuOrganizationShort] = {}
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("projectID")
organization_id = source.get("organisationID")
ec_contribution = source.get("ecContribution")
if project_id and organization_id:
project_contributions[project_id] = EuOrganizationShort(
project_id=project_id,
organization_id=organization_id,
ec_contribution=ec_contribution,
)
return project_contributions
def get_eu_organization_projects(
project_contributions: List[EuOrganizationShort],
projects_filtering_properties: ProjectsFilteringProperties,
) -> Tuple[int, Dict[str, EuProjectShort]]:
"""Fetches the projects associated with the given list of organization contributions, applying the specified filtering properties.
Args:
project_contributions (List[EuOrganizationShort]): The list of organization contributions to fetch projects for.
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties to apply to the project search.
Returns:
Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details.
"""
project_ids = [contribution.project_id for contribution in project_contributions]
source = ["id", "title", "startDate", "endDate", "acronym"]
query = {
"terms": {
"id": project_ids,
}
}
if (
projects_filtering_properties.query
and projects_filtering_properties.query.strip()
):
query = {
"bool": {
"must": [
{
"match_phrase_prefix": {
"title": {
"query": projects_filtering_properties.query,
"max_expansions": 50,
}
}
}
],
"filter": query,
}
}
# Project contributions have been filtered before based on ecContribution
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
query=query,
size=10000,
)
else:
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
query=query,
size=projects_filtering_properties.size,
offset=projects_filtering_properties.page
* projects_filtering_properties.size,
sort=[
{
projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): {
"order": projects_filtering_properties.sort_direction
}
}
],
)
return _process_projects_response(response)
def _process_projects_response(
response: Dict[str, Any],
) -> Tuple[int, Dict[str, EuProjectShort]]:
"""Processes the raw Elasticsearch response to extract the project details and total count.
Args:
response (Dict[str, Any]): The raw Elasticsearch response.
Returns:
Tuple[int, Dict[str, EuProjectShort]]: A tuple containing the total number of projects and a dictionary mapping project IDs to their corresponding project details.
"""
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
projects: Dict[str, EuProjectShort] = {}
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("id")
title = source.get("title")
start_date = source.get("startDate")
end_date = source.get("endDate")
acronym = source.get("acronym")
if not project_id:
continue
projects[project_id] = EuProjectShort(
id=project_id,
title=title,
start_date=start_date,
end_date=end_date,
acronym=acronym,
)
return total, projects
def _merge_project_data(
projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort]
) -> List[EuOrganizationProjectSummary]:
"""Merges the project details with the organization contributions to create a list of EuOrganizationProjectSummary objects.
Args:
projects (Dict[str, EuProjectShort]): The dictionary of project details.
contributions (Dict[str, EuOrganizationShort]): The dictionary of organization contributions.
Returns:
List[EuOrganizationProjectSummary]: The list of merged project-summary objects.
"""
merged_data = []
for project_id, project_info in projects.items():
contribution_info = contributions.get(project_id)
if contribution_info:
merged_entry = EuOrganizationProjectSummary(
project_id=project_id,
title=project_info.title,
start_date=project_info.start_date,
end_date=project_info.end_date,
acronym=project_info.acronym,
organization_id=contribution_info.organization_id,
ec_contribution=contribution_info.ec_contribution,
)
merged_data.append(merged_entry)
return merged_data
def _get_raw_doi(doi: str) -> str:
"""Extracts the raw DOI from a given DOI string, removing any URL prefixes if present.
@@ -304,6 +557,9 @@ def get_cordis_eu_projects_by_project_ids(
)
# DFG
def search_dfg_projects(
page: int,
size: int,
@@ -311,7 +567,20 @@ def search_dfg_projects(
topic: Optional[str] = None,
sort_by: str = "id",
sort_direction: str = "asc",
):
) -> DfgProjectPage:
"""Searches for DFG projects based on the provided filtering and sorting criteria.
Args:
page (int): The page number.
size (int): The number of items per page.
names (Optional[List[str]], optional): The list of names to search for. Defaults to None.
topic (Optional[str], optional): The topic to search for. Defaults to None.
sort_by (str, optional): The field to sort by. Defaults to "id".
sort_direction (str, optional): The direction to sort. Defaults to "asc".
Returns:
DfgProjectPage: The search results.
"""
from_ = page * size
painless_fields_string = ", ".join([f"'{f}.keyword'" for f in DFG_PERSON_FIELDS])
@@ -471,6 +740,16 @@ def search_dfg_projects(
def _complete_response_to_dfg_project_page(
response: dict, page: int, size: int
) -> DfgProjectPage:
"""Converts the raw Elasticsearch response into a DfgProjectPage object.
Args:
response (dict): The raw Elasticsearch response.
page (int): The page number.
size (int): The number of items per page.
Returns:
DfgProjectPage: The converted project page object.
"""
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [DfgProjectSummary.from_hit(hit) for hit in hits_block.get("hits", [])]
@@ -478,6 +757,14 @@ def _complete_response_to_dfg_project_page(
def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
"""Fetches the details of a single DFG project based on its project ID.
Args:
project_id (str): The project ID to fetch.
Returns:
Optional[DfgProjectDetails]: The project details or None if not found.
"""
query = {"ids": {"values": [project_id]}}
response = elasticsearch.search(
@@ -494,10 +781,25 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
return None
# All
def search_all_projects(
projects_filtering_properties: ProjectsFilteringProperties,
selected_project_types: Optional[Set[ProjectType]] = None,
):
) -> FundingProjectPage:
"""Searches for projects across all project types based on the provided filtering properties and selected project types.
Args:
projects_filtering_properties (ProjectsFilteringProperties): The filtering properties for the search.
selected_project_types (Optional[Set[ProjectType]], optional): The set of project types to include in the search. Defaults to None -> includes all project types.
Raises:
ValueError: If the sorting property is not supported across all project types.
Returns:
FundingProjectPage: The converted project page object.
"""
sort_by = projects_filtering_properties.sort_by
if sort_by != ProjectsSortBy.TITLE:
raise ValueError(
@@ -573,6 +875,16 @@ def search_all_projects(
def _response_to_funding_project_page(
response: Dict[str, Any], page: int, size: int
) -> FundingProjectPage:
"""Converts the raw Elasticsearch response into a FundingProjectPage object.
Args:
response (Dict[str, Any]): The raw Elasticsearch response.
page (int): The current page number.
size (int): The number of projects per page.
Returns:
FundingProjectPage: The converted project page object.
"""
hits = response.get("hits", {}).get("hits", [])
projects = [_hit_to_funding_project(hit=hit) for hit in hits]
total = response.get("hits", {}).get("total", {}).get("value", 0)
@@ -580,219 +892,26 @@ def _response_to_funding_project_page(
def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject:
"""Converts a single Elasticsearch hit into a FundingProject object based on the index it belongs to.
Args:
hit (Dict[str, Any]): The Elasticsearch hit to convert.
Raises:
ValueError: If the hit does not belong to a recognized project index.
Returns:
FundingProject: The converted funding project object.
"""
if hit.get("_index", "").startswith("cordis_eu_") and hit.get(
"_index", ""
).endswith("_projects"):
return FundingProject.from_cordis_projects_hit(hit=hit)
elif hit.get("_index") == "projects_bund_v1":
elif hit.get("_index") == ESIndex.PROJECTS_BUND_V1.value:
return FundingProject.from_bund_projects_hit(hit=hit)
elif hit.get("_index") == "projects_dfg_all":
elif hit.get("_index") == ESIndex.PROJECTS_DFG_ALL.value:
return FundingProject.from_dfg_projects_hit(hit=hit)
else:
raise ValueError(
"The provided hit does not belong to a recognized project index."
)
def get_organization_project_contributions_foo(
organization_names: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
# Pagination depending on sorting criteria
# For FUNDING_AMOUNT before on the organization project contributions
# For the rest after the contributions are known on the real projects
organization_project_contributions = get_organization_project_contributions(
organization_names=organization_names,
)
total_projects, projects = get_projects(
project_contributions=list(organization_project_contributions.values()),
projects_filtering_properties=projects_filtering_properties,
)
elements: List[EuOrganizationProjectSummary] = _merge_project_data(
projects=projects, contributions=organization_project_contributions
)
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
elements.sort(
key=lambda x: x.ec_contribution or 0,
reverse=projects_filtering_properties.sort_direction == SortDirection.DESC,
)
start = projects_filtering_properties.page * projects_filtering_properties.size
end = start + projects_filtering_properties.size
elements = elements[start:end]
return EuOrganizationProjectSummaryPage(
elements=elements,
total=total_projects,
page=projects_filtering_properties.page,
size=projects_filtering_properties.size,
)
def get_organization_project_contributions(
organization_names: List[str],
) -> Dict[str, EuOrganizationShort]:
source = ["projectID", "organisationID", "ecContribution"]
query = {
"terms": {
"name.keyword": [
name.upper() for name in organization_names if name.strip()
],
}
}
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
size=10000,
query=query,
)
logger.debug(
f"Received organization project contributions response: {json.dumps(response, indent=2)}"
)
organization_project_contributions = _process_organization_project_contributions(
response
)
logger.debug(
f"Found organization project contributions for organization names {organization_names}: {organization_project_contributions}"
)
return organization_project_contributions
def _process_organization_project_contributions(
response: Dict[str, Any],
) -> Dict[str, EuOrganizationShort]:
hits_block = response.get("hits", {})
project_contributions: Dict[str, EuOrganizationShort] = {}
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("projectID")
organization_id = source.get("organisationID")
ec_contribution = source.get("ecContribution")
if project_id and organization_id:
project_contributions[project_id] = EuOrganizationShort(
project_id=project_id,
organization_id=organization_id,
ec_contribution=ec_contribution,
)
return project_contributions
def get_projects(
project_contributions: List[EuOrganizationShort],
projects_filtering_properties: ProjectsFilteringProperties,
) -> Tuple[int, Dict[str, EuProjectShort]]:
project_ids = [contribution.project_id for contribution in project_contributions]
source = ["id", "title", "startDate", "endDate", "acronym"]
query = {
"terms": {
"id": project_ids,
}
}
if (
projects_filtering_properties.query
and projects_filtering_properties.query.strip()
):
query = {
"bool": {
"must": [
{
"match_phrase_prefix": {
"title": {
"query": projects_filtering_properties.query,
"max_expansions": 50,
}
}
}
],
"filter": query,
}
}
# Project contributions have been filtered before based on ecContribution
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
query=query,
size=10000,
)
else:
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
query=query,
size=projects_filtering_properties.size,
offset=projects_filtering_properties.page
* projects_filtering_properties.size,
sort=[
{
projects_filtering_properties.sort_by.to_cordis_eu_project_sort_field(): {
"order": projects_filtering_properties.sort_direction
}
}
],
)
return _process_projects_response(response)
def _process_projects_response(
response: Dict[str, Any],
) -> Tuple[int, Dict[str, EuProjectShort]]:
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
projects: Dict[str, EuProjectShort] = {}
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("id")
title = source.get("title")
start_date = source.get("startDate")
end_date = source.get("endDate")
acronym = source.get("acronym")
if not project_id:
continue
projects[project_id] = EuProjectShort(
id=project_id,
title=title,
start_date=start_date,
end_date=end_date,
acronym=acronym,
)
return total, projects
def _merge_project_data(
projects: Dict[str, EuProjectShort], contributions: Dict[str, EuOrganizationShort]
) -> List[EuOrganizationProjectSummary]:
merged_data = []
for project_id, project_info in projects.items():
contribution_info = contributions.get(project_id)
if contribution_info:
merged_entry = EuOrganizationProjectSummary(
project_id=project_id,
title=project_info.title,
start_date=project_info.start_date,
end_date=project_info.end_date,
acronym=project_info.acronym,
organization_id=contribution_info.organization_id,
ec_contribution=contribution_info.ec_contribution,
)
merged_data.append(merged_entry)
return merged_data
+9 -10
View File
@@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optional, Set
from inse.projects import projects_search_client
from inse.projects.projects_search_client import (
get_organization_project_contributions_foo,
get_eu_organization_project_contributions,
)
from inse.projects.model import (
BundProjectPage,
@@ -90,12 +90,8 @@ def get_bund_projects_by_institution_id(
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
response = projects_search_client.search_bund_projects(
page=filtering_properties.page,
size=filtering_properties.size,
institution_names=institution_aliases,
topic=filtering_properties.query,
sort_by=filtering_properties.sort_by,
sort_direction=filtering_properties.sort_direction,
filter_properties=filtering_properties,
)
logger.debug(f"get_bund_projects_by_institution_id response: {response}")
return response
@@ -137,7 +133,7 @@ def get_cordis_eu_projects_by_institution_id(
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
page = get_organization_project_contributions_foo(
page = get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=projects_filtering_properties,
)
@@ -186,7 +182,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
raw_oa_institution_id
)
)
page = get_organization_project_contributions_foo(
page = get_eu_organization_project_contributions(
organization_names=institution_aliases,
projects_filtering_properties=ProjectsFilteringProperties(
project_type=ProjectType.EU,
@@ -220,8 +216,11 @@ def get_institution_bund_projects_funding_over_time(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
response = projects_search_client.search_bund_projects(
page=0,
size=10000,
filter_properties=ProjectsFilteringProperties(
project_type=ProjectType.BUND,
page=0,
size=10000,
),
institution_names=institution_aliases,
)