Moved dfg projects search client out of class

This commit is contained in:
Mats Paul Tončik
2026-06-21 15:35:56 +02:00
parent 9cd109fc17
commit f3539e4210
5 changed files with 354 additions and 697 deletions
@@ -1,3 +1,4 @@
import json
import logging
from typing import Any, Dict, List, Optional, Tuple
import httpx
@@ -154,7 +155,7 @@ def search(
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {payload}"
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
)
if isinstance(index, list):
index_str = ",".join(index)
+1 -1
View File
@@ -53,7 +53,7 @@ def search_persons(
if include
else None
)
return logic.search_persons(author_id, query, include_set)
return logic.search_persons(author_id, query)
@router.get(
@@ -133,642 +133,365 @@ class ProjectsSearchClient:
return response.json()
class BundProjectsSearchClient(ProjectsSearchClient):
def __init__(self):
if not settings.elasticsearch_inse_url:
raise ValueError("Elasticsearch INSE URL is missing in settings.")
if not settings.elasticsearch_inse_api_key:
raise ValueError("Elasticsearch INSE API key is missing in settings.")
super().__init__(
base_url=settings.elasticsearch_inse_url,
index="projects_bund_v1",
api_key=settings.elasticsearch_inse_api_key,
)
def search_bund_projects(
page: int,
size: int,
institution_names: List[str] = [],
topic: Optional[str] = None,
sort_by: ProjectsSortBy = ProjectsSortBy.TITLE,
sort_direction: SortDirection = SortDirection.ASC,
) -> BundProjectPage:
def _bund_projects_query(
self,
page: int,
size: int,
id: Optional[str] = None,
institution_names: List[str] = [],
topic: Optional[str] = None,
sort_by: ProjectsSortBy = ProjectsSortBy.TITLE,
sort_direction: SortDirection = SortDirection.ASC,
) -> dict:
from_ = page * size
query: Dict[str, Any] = {"size": size, "from": from_, "query": {}}
must_clauses: List[Dict[str, Any]] = []
if id:
must_clauses.append({"match": {"id": id}})
if len(institution_names) > 0:
must_clauses.append(
{
"bool": {
"should": [
{
"match": {
"Zuwendungsempfänger": {
"query": name,
"operator": "and",
}
must_clauses: List[Dict[str, Any]] = []
if len(institution_names) > 0:
must_clauses.append(
{
"bool": {
"should": [
{
"match": {
"Zuwendungsempfänger": {
"query": name,
"operator": "and",
}
}
for name in institution_names
],
"minimum_should_match": 1,
}
}
)
if topic is not None and topic.strip() != "":
must_clauses.append(
{
"match_phrase_prefix": {
"Thema": {
"query": topic,
"max_expansions": 50,
}
for name in institution_names
],
"minimum_should_match": 1,
}
}
)
if topic is not None and topic.strip() != "":
must_clauses.append(
{
"match_phrase_prefix": {
"Thema": {
"query": topic,
"max_expansions": 50,
}
}
)
if must_clauses:
query["query"] = {"bool": {"must": must_clauses}}
else:
query["query"] = {"match_all": {}}
query["sort"] = [
{sort_by.to_bund_project_sort_field(): {"order": sort_direction}}
]
query_str = json.dumps(query, indent=2)
logger.debug(f"Constructed Bund project query: {query_str}")
return query
def response_to_bund_project_page(
self, response: dict, page: int, size: int
) -> BundProjectPage:
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
BundProject.model_validate(hit["_source"])
for hit in hits_block.get("hits", [])
]
return BundProjectPage(
elements=elements, total=total_hits, page=page, size=size
}
)
async def search_bund_projects(
self,
page: int,
size: int,
id: Optional[str] = None,
institution_names: List[str] = [],
topic: Optional[str] = None,
sort_by: ProjectsSortBy = ProjectsSortBy.TITLE,
sort_direction: SortDirection = SortDirection.ASC,
) -> BundProjectPage:
query = self._bund_projects_query(
page=page,
size=size,
id=id,
institution_names=institution_names,
topic=topic,
sort_by=sort_by,
sort_direction=sort_direction,
)
response = await self.make_search_request(query)
return self.response_to_bund_project_page(response, page, size)
query: Optional[Dict[str, Any]] = None
if must_clauses:
query = {"bool": {"must": must_clauses}}
async def get_bund_projects_by_institution_name(
self,
institution_names: List[str],
page: int,
size: int,
sort_by: str = "topic",
sort_direction: str = "asc",
) -> BundProjectPage:
query = self._bund_projects_query(
page=page,
size=size,
institution_names=institution_names,
sort_by=sort_by,
sort_direction=sort_direction,
)
response = await self.make_search_request(query)
return self.response_to_bund_project_page(response, page, size)
sort = [{sort_by.to_bund_project_sort_field(): {"order": sort_direction.value}}]
async def get_bund_project_by_id(
self, project_id: str
) -> Optional[BundProjectDetails]:
response = elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=query,
sort=sort,
size=size,
offset=page * size,
)
query = {
"query": {"term": {"Förderkennzeichen.keyword": {"value": project_id}}},
"_source": True,
}
response = await self.make_search_request(query)
hits = response.get("hits", {}).get("hits", [])
if hits:
hit = hits[0]
print(hit)
details = BundProjectDetails.from_elastic_hit(hit=hit)
return details
return None
return _complete_response_to_bund_project_page(
response=response, page=page, size=size
)
class EuProjectsSearchClient(ProjectsSearchClient):
def __init__(self):
if not settings.elasticsearch_inse_url:
raise ValueError("Elasticsearch INSE URL is missing in settings.")
if not settings.elasticsearch_inse_api_key:
raise ValueError("Elasticsearch INSE API key is missing in settings.")
super().__init__(
base_url=settings.elasticsearch_inse_url,
index="projects_eu_all",
api_key=settings.elasticsearch_inse_api_key,
)
def _complete_response_to_bund_project_page(
response: Dict[str, Any], page: int, size: int
) -> BundProjectPage:
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
BundProject.model_validate(hit["_source"]) for hit in hits_block.get("hits", [])
]
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
def _eu_projects_id_body(self, eu_organisation_ids: List[str]) -> Dict[str, Any]:
"""Constructs the Elasticsearch query body to retrieve project IDs associated with the given list of EU organisation IDs.
Args:
eu_organisation_ids (List[str]): A list of EU organisation IDs for which to retrieve associated project IDs.
def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
query = {"term": {"Förderkennzeichen.keyword": {"value": project_id}}}
Returns:
Dict[str, Any]: The Elasticsearch query body.
"""
body: Dict[str, Any] = {
"size": 0,
"query": {
"bool": {"filter": [{"terms": {"organisationID": eu_organisation_ids}}]}
},
"aggs": {
"associated_project_ids": {
"terms": {"field": "projectID", "size": 10000}
response = elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=query,
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if hits:
hit = hits[0]
details = BundProjectDetails.from_elastic_hit(hit=hit)
return details
return None
def _get_raw_doi(doi: str) -> str:
"""Extracts the raw DOI from a given DOI string, removing any URL prefixes if present.
Args:
doi (str): The DOI string to process.
Returns:
str: The raw DOI string.
"""
if doi.startswith("https://doi.org/"):
return doi[len("https://doi.org/") :]
elif doi.startswith("http://dx.doi.org/"):
return doi[len("http://dx.doi.org/") :]
else:
return doi
def get_cordis_eu_publications_by_dois(dois: List[str]):
"""Retrieves Cordis EU publications associated with the given list of DOIs.
Args:
dois (List[str]): The list of DOIs for which to retrieve publications.
Returns:
_type_: The retrieved publications.
"""
raw_dois = [_get_raw_doi(doi) for doi in dois]
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
)
logger.debug(f"Received publications response: {json.dumps(response, indent=2)}")
return response
def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
"""Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs.
Args:
dois (List[str]): The list of DOIs for which to retrieve project IDs.
Returns:
List[str]: The list of project IDs.
"""
response = get_cordis_eu_publications_by_dois(dois=dois)
hits_block = response.get("hits", {})
project_ids = set()
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("projectID")
if project_id:
project_ids.add(project_id)
return list(project_ids)
def get_cordis_eu_projects_by_project_ids(
project_ids: List[str],
) -> CordisEuProjectPage:
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
)
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
CordisEuProject.model_validate(hit["_source"])
for hit in hits_block.get("hits", [])
]
return CordisEuProjectPage(
elements=elements, total=total_hits, page=0, size=len(elements)
)
def search_dfg_projects(
page: int,
size: int,
names: Optional[List[str]] = None,
topic: Optional[str] = None,
sort_by: str = "id",
sort_direction: str = "asc",
):
from_ = page * size
painless_fields_string = ", ".join([f"'{f}.keyword'" for f in DFG_PERSON_FIELDS])
body: Dict[str, Any] = {
"size": size,
"from": from_,
"_source": [
"id",
"link",
"title",
"funding_start",
"funding_end",
"Fachliche Zuordnung",
],
"query": {},
"script_fields": {
"all_found_names": {
"script": {
"lang": "painless",
"source": (
f"def names = new HashSet(); "
f"def fields = [{painless_fields_string}]; "
f"for (field in fields) {{ "
f" if (doc.containsKey(field) && !doc[field].empty) {{ "
f" for (value in doc[field]) {{ "
f" if (value.contains(';')) {{ "
f" def splitNames = value.splitOnToken(';'); "
f" for (sn in splitNames) {{ names.add(sn.trim()); }} "
f" }} else {{ "
f" names.add(value.trim()); "
f" }} "
f" }} "
f" }} "
f"}} "
f"return new ArrayList(names);"
),
}
},
}
}
},
}
query_str = json.dumps(body, indent=2)
logger.debug(f"Constructed EU project ID query: {query_str}")
return body
must_clauses: List[Dict[str, Any]] = []
filter_clauses: List[Dict[str, Any]] = []
def _eu_projects_id_response_to_ids(self, response: Dict[str, Any]) -> List[str]:
"""Converts the Elasticsearch aggregation response to a list of project IDs.
Args:
response (Dict[str, Any]): The Elasticsearch aggregation response.
Returns:
List[str]: A list of project IDs.
"""
buckets = (
response.get("aggregations", {})
.get("associated_project_ids", {})
.get("buckets", [])
)
ids = [bucket.get("key") for bucket in buckets if "key" in bucket]
logger.debug(f"Extracted project IDs from response: {ids}")
return ids
def _eu_project_sort_by_field(self, sort_by: ProjectsSortBy) -> str:
"""Maps the ProjectsSortBy enum to the corresponding Elasticsearch field for sorting EU projects.
Args:
sort_by (ProjectsSortBy): The sorting criterion specified as a ProjectsSortBy enum value.
Returns:
str: The corresponding Elasticsearch field for sorting.
"""
if sort_by == ProjectsSortBy.TITLE:
return "title.keyword"
elif sort_by == ProjectsSortBy.FUNDING_START:
return "startDate"
elif sort_by == ProjectsSortBy.FUNDING_END:
return "endDate"
elif sort_by == ProjectsSortBy.FUNDING_AMOUNT:
return "totalCost"
else:
return "id.keyword"
def _eu_projects_body(
self,
project_ids: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> Dict[str, Any]:
bool_query: Dict[str, Any] = {"filter": [{"terms": {"id": project_ids}}]}
if (
projects_filtering_properties.query is not None
and projects_filtering_properties.query.strip() != ""
):
bool_query["must"] = [
{
"match_phrase_prefix": {
"title": {
"query": projects_filtering_properties.query,
"max_expansions": 50,
}
if topic is not None and topic.strip() != "":
must_clauses.append(
{
"match_phrase_prefix": {
"title": {
"query": topic,
"max_expansions": 100,
}
}
}
)
if names:
name_should_clauses = []
script_conditions = []
for full_name in names:
name_parts = full_name.strip().split()
if not name_parts:
continue
match_musts = []
for part in name_parts:
match_musts.append(
{"multi_match": {"query": part, "fields": DFG_PERSON_FIELDS}}
)
name_should_clauses.append({"bool": {"must": match_musts}})
script_parts = [
f"singlePerson.contains('{part.lower()}')" for part in name_parts
]
script_conditions.append(f"({' && '.join(script_parts)})")
body: Dict[str, Any] = {
"from": projects_filtering_properties.page
* projects_filtering_properties.size,
"size": projects_filtering_properties.size,
"query": {"bool": bool_query},
"sort": [
{
self._eu_project_sort_by_field(
projects_filtering_properties.sort_by
): {
"order": projects_filtering_properties.sort_direction,
}
}
],
}
query_str = json.dumps(body, indent=2)
logger.debug(f"Constructed EU project details query: {query_str}")
return body
async def search_eu_projects(
self,
eu_organisation_ids: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> CordisEuProjectPage:
projects_id_body = self._eu_projects_id_body(eu_organisation_ids)
id_response = await self.make_search_request(
projects_id_body, index="cordis_eu_*_organizations"
)
project_ids = self._eu_projects_id_response_to_ids(id_response)
logger.debug(
f"Found project IDs for organization IDs {eu_organisation_ids}: {project_ids}"
)
if not project_ids:
logger.debug(
f"No project IDs found for organization IDs {eu_organisation_ids}"
)
return CordisEuProjectPage(
elements=[],
total=0,
page=projects_filtering_properties.page,
size=projects_filtering_properties.size,
)
projects_body = self._eu_projects_body(
project_ids=project_ids,
projects_filtering_properties=projects_filtering_properties,
)
projects_response = await self.make_search_request(
projects_body, index="cordis_eu_*_projects"
)
logger.debug(
f"Received projects response: {json.dumps(projects_response, indent=2)}"
)
return self._response_to_cordis_eu_project_page(
projects_response,
projects_filtering_properties.page,
projects_filtering_properties.size,
)
def _response_to_cordis_eu_project_page(
self, response: Dict[str, Any], page: int, size: int
) -> CordisEuProjectPage:
"""Converts the Elasticsearch response to a CordisEuProjectPage containing CordisEuProject elements.
Args:
response (Dict[str, Any]): The Elasticsearch response.
page (int): The page number.
size (int): The number of items per page.
Returns:
CordisEuProjectPage: The converted project page.
"""
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
CordisEuProject.model_validate(hit["_source"])
for hit in hits_block.get("hits", [])
]
return CordisEuProjectPage(
elements=elements, total=total_hits, page=page, size=size
)
def _get_raw_doi(self, doi: str) -> str:
"""Extracts the raw DOI from a given DOI string, removing any URL prefixes if present.
Args:
doi (str): The DOI string to process.
Returns:
str: The raw DOI string.
"""
if doi.startswith("https://doi.org/"):
return doi[len("https://doi.org/") :]
elif doi.startswith("http://dx.doi.org/"):
return doi[len("http://dx.doi.org/") :]
else:
return doi
def get_cordis_eu_publications_by_dois(self, dois: List[str]):
"""Retrieves Cordis EU publications associated with the given list of DOIs.
Args:
dois (List[str]): The list of DOIs for which to retrieve publications.
Returns:
_type_: The retrieved publications.
"""
raw_dois = [self._get_raw_doi(doi) for doi in dois]
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
)
logger.debug(
f"Received publications response: {json.dumps(response, indent=2)}"
)
return response
def get_cordis_eu_project_ids_by_dois(self, dois: List[str]) -> List[str]:
"""Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs.
Args:
dois (List[str]): The list of DOIs for which to retrieve project IDs.
Returns:
List[str]: The list of project IDs.
"""
response = self.get_cordis_eu_publications_by_dois(dois=dois)
hits_block = response.get("hits", {})
project_ids = set()
for hit in hits_block.get("hits", []):
source = hit.get("_source", {})
project_id = source.get("projectID")
if project_id:
project_ids.add(project_id)
return list(project_ids)
def get_cordis_eu_projects_by_project_ids(
self, project_ids: List[str]
) -> CordisEuProjectPage:
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
)
hits_block = response.get("hits", {})
total_hits = hits_block.get("total", {}).get("value", 0)
elements = [
CordisEuProject.model_validate(hit["_source"])
for hit in hits_block.get("hits", [])
]
return CordisEuProjectPage(
elements=elements, total=total_hits, page=0, size=len(elements)
)
class DfgProjectsSearchClient(ProjectsSearchClient):
def __init__(self):
if not settings.elasticsearch_inse_url:
raise ValueError("Elasticsearch INSE URL is missing in settings.")
if not settings.elasticsearch_inse_api_key:
raise ValueError("Elasticsearch INSE API key is missing in settings.")
super().__init__(
base_url=settings.elasticsearch_inse_url,
index="projects_dfg_all",
api_key=settings.elasticsearch_inse_api_key,
)
def dfg_projects_query(
self,
page: int,
size: int,
names: Optional[List[str]] = None,
topic: Optional[str] = None,
sort_by: str = "id",
sort_direction: str = "asc",
) -> dict:
from_ = page * size
painless_fields_string = ", ".join(
[f"'{f}.keyword'" for f in DFG_PERSON_FIELDS]
)
query: Dict[str, Any] = {
"size": size,
"from": from_,
"_source": [
"id",
"link",
"title",
"funding_start",
"funding_end",
"Fachliche Zuordnung",
],
"query": {},
"script_fields": {
"all_found_names": {
"script": {
"lang": "painless",
"source": (
f"def names = new HashSet(); "
f"def fields = [{painless_fields_string}]; "
f"for (field in fields) {{ "
f" if (doc.containsKey(field) && !doc[field].empty) {{ "
f" for (value in doc[field]) {{ "
f" if (value.contains(';')) {{ "
f" def splitNames = value.splitOnToken(';'); "
f" for (sn in splitNames) {{ names.add(sn.trim()); }} "
f" }} else {{ "
f" names.add(value.trim()); "
f" }} "
f" }} "
f" }} "
f"}} "
f"return new ArrayList(names);"
),
}
}
},
}
must_clauses: List[Dict[str, Any]] = []
filter_clauses: List[Dict[str, Any]] = []
if topic is not None and topic.strip() != "":
if name_should_clauses:
must_clauses.append(
{
"match_phrase_prefix": {
"title": {
"query": topic,
"max_expansions": 100,
}
}
}
{"bool": {"should": name_should_clauses, "minimum_should_match": 1}}
)
if names:
name_should_clauses = []
script_conditions = []
combined_script_condition = " || ".join(script_conditions)
painless_source = (
f"def fields = [{painless_fields_string}]; "
f"for (field in fields) {{ "
f" if (doc.containsKey(field) && !doc[field].empty) {{ "
f" for (value in doc[field]) {{ "
f" if (value.contains(';')) {{ "
f" def splitValues = value.splitOnToken(';'); "
f" for (singlePersonRaw in splitValues) {{ "
f" def singlePerson = singlePersonRaw.toLowerCase(); "
f" if ({combined_script_condition}) {{ return true; }} "
f" }} "
f" }} else {{ "
f" def singlePerson = value.toLowerCase(); "
f" if ({combined_script_condition}) {{ return true; }} "
f" }} "
f" }} "
f" }} "
f"}} "
f"return false;"
)
for full_name in names:
name_parts = full_name.strip().split()
if not name_parts:
continue
filter_clauses.append(
{"script": {"script": {"lang": "painless", "source": painless_source}}}
)
match_musts = []
for part in name_parts:
match_musts.append(
{"multi_match": {"query": part, "fields": DFG_PERSON_FIELDS}}
)
if must_clauses or filter_clauses:
body["query"] = {"bool": {}}
if must_clauses:
body["query"]["bool"]["must"] = must_clauses
if filter_clauses:
body["query"]["bool"]["filter"] = filter_clauses
else:
body["query"] = {"match_all": {}}
name_should_clauses.append({"bool": {"must": match_musts}})
sort_by = sort_by.strip().lower()
sort_direction = sort_direction.strip().lower()
if sort_direction not in ["asc", "desc"]:
sort_direction = "asc"
logger.debug(f"Sorting DFG projects by {sort_by} with direction {sort_direction}")
script_parts = [
f"singlePerson.contains('{part.lower()}')" for part in name_parts
]
script_conditions.append(f"({' && '.join(script_parts)})")
if name_should_clauses:
must_clauses.append(
{"bool": {"should": name_should_clauses, "minimum_should_match": 1}}
)
combined_script_condition = " || ".join(script_conditions)
painless_source = (
f"def fields = [{painless_fields_string}]; "
f"for (field in fields) {{ "
f" if (doc.containsKey(field) && !doc[field].empty) {{ "
f" for (value in doc[field]) {{ "
f" if (value.contains(';')) {{ "
f" def splitValues = value.splitOnToken(';'); "
f" for (singlePersonRaw in splitValues) {{ "
f" def singlePerson = singlePersonRaw.toLowerCase(); "
f" if ({combined_script_condition}) {{ return true; }} "
f" }} "
f" }} else {{ "
f" def singlePerson = value.toLowerCase(); "
f" if ({combined_script_condition}) {{ return true; }} "
f" }} "
f" }} "
f" }} "
f"}} "
f"return false;"
)
filter_clauses.append(
{
"script": {
"script": {"lang": "painless", "source": painless_source}
}
}
)
if must_clauses or filter_clauses:
query["query"] = {"bool": {}}
if must_clauses:
query["query"]["bool"]["must"] = must_clauses
if filter_clauses:
query["query"]["bool"]["filter"] = filter_clauses
else:
query["query"] = {"match_all": {}}
sort_by = sort_by.strip().lower()
sort_direction = sort_direction.strip().lower()
if sort_direction not in ["asc", "desc"]:
sort_direction = "asc"
if sort_by in ["topic", "title"]:
logger.debug(f"Sorting DFG projects by title with direction {sort_direction}")
sort_config = {"title.keyword": {"order": sort_direction}}
elif sort_by == "funding_start":
logger.debug(
f"Sorting DFG projects by {sort_by} with direction {sort_direction}"
f"Sorting DFG projects by funding_start with direction {sort_direction}"
)
if sort_by in ["topic", "title"]:
logger.debug(
f"Sorting DFG projects by title with direction {sort_direction}"
)
sort_config = {"title.keyword": {"order": sort_direction}}
elif sort_by == "funding_start":
logger.debug(
f"Sorting DFG projects by funding_start with direction {sort_direction}"
)
sort_config = {"funding_start.keyword": {"order": sort_direction}}
elif sort_by == "funding_end":
logger.debug(
f"Sorting DFG projects by funding_end with direction {sort_direction}"
)
sort_config = {"funding_end.keyword": {"order": sort_direction}}
elif sort_by == "professional_classification":
logger.debug(
f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}"
)
sort_config = {"Fachliche Zuordnung.keyword": {"order": sort_direction}}
else:
logger.debug(f"Sorting DFG projects by id with direction {sort_direction}")
sort_config = {"id.keyword": {"order": sort_direction}}
query["sort"] = [sort_config]
query_str = json.dumps(query, indent=2)
logger.debug(f"Constructed DFG project query: {query_str}")
return query
def response_to_dfg_project_page(
self, response: dict, page: int, size: int
) -> DfgProjectPage:
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", [])
]
return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size)
async def search_dfg_projects(
self,
page: int,
size: int,
names: Optional[List[str]] = None,
topic: Optional[str] = None,
sort_by: str = "id",
sort_direction: str = "asc",
) -> DfgProjectPage:
query = self.dfg_projects_query(
page=page,
size=size,
names=names,
topic=topic,
sort_by=sort_by,
sort_direction=sort_direction,
sort_config = {"funding_start.keyword": {"order": sort_direction}}
elif sort_by == "funding_end":
logger.debug(
f"Sorting DFG projects by funding_end with direction {sort_direction}"
)
response = await self.make_search_request(query)
return self.response_to_dfg_project_page(response, page, size)
sort_config = {"funding_end.keyword": {"order": sort_direction}}
elif sort_by == "professional_classification":
logger.debug(
f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}"
)
sort_config = {"Fachliche Zuordnung.keyword": {"order": sort_direction}}
else:
logger.debug(f"Sorting DFG projects by id with direction {sort_direction}")
sort_config = {"id.keyword": {"order": sort_direction}}
async def get_dfg_project_by_id(
self, project_id: str
) -> Optional[DfgProjectDetails]:
query = {"query": {"ids": {"values": [project_id]}}, "_source": True}
body["sort"] = [sort_config]
response = await self.make_search_request(query)
hits = response.get("hits", {}).get("hits", [])
response = elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
body=body,
)
return _complete_response_to_dfg_project_page(response, page, size)
if hits:
hit = hits[0]
details = DfgProjectDetails.from_elastic_hit(hit=hit)
return details
return None
def _complete_response_to_dfg_project_page(
response: dict, page: int, size: int
) -> DfgProjectPage:
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", [])]
return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size)
def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
query = {"ids": {"values": [project_id]}}
response = elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
query=query,
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if hits:
hit = hits[0]
details = DfgProjectDetails.from_elastic_hit(hit=hit)
return details
return None
def search_all_projects(
+8 -54
View File
@@ -20,11 +20,7 @@ from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.tags import Tags
from inse.projects import service as projects_service
from inse.projects.projects_search_client import (
BundProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
)
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
@@ -35,21 +31,6 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
@lru_cache
def get_bund_search_client() -> BundProjectsSearchClient:
return BundProjectsSearchClient()
@lru_cache
def get_eu_search_client() -> EuProjectsSearchClient:
return EuProjectsSearchClient()
@lru_cache
def get_dfg_search_client() -> DfgProjectsSearchClient:
return DfgProjectsSearchClient()
@router.get(
"/author/{raw_oa_author_id}/eu",
summary="Get EU projects for an author.",
@@ -65,16 +46,12 @@ def get_dfg_search_client() -> DfgProjectsSearchClient:
response_model_by_alias=False,
)
def get_eu_projects_for_author(
eu_projects_search_client: Annotated[
EuProjectsSearchClient, Depends(get_eu_search_client)
],
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
) -> CordisEuProjectPage:
logger.debug(
f"Received request to get EU projects for author_id={raw_oa_author_id}"
)
return projects_service.search_cordis_eu_projects_for_author_id(
eu_projects_search_client=eu_projects_search_client,
raw_oa_author_id=raw_oa_author_id,
)
@@ -94,9 +71,6 @@ def get_eu_projects_for_author(
response_model_by_alias=False,
)
async def search_bund_projects(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -105,8 +79,7 @@ async def search_bund_projects(
Body(description="The filtering properties for the projects search."),
],
) -> BundProjectPage:
return await projects_service.search_bund_projects(
bund_search_client=bund_search_client,
return projects_service.search_bund_projects(
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
@@ -126,15 +99,11 @@ async def search_bund_projects(
},
response_model_by_alias=False,
)
async def get_single_dfg_project(
dfg_search_client: Annotated[
DfgProjectsSearchClient, Depends(get_dfg_search_client)
],
def get_single_dfg_project(
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
) -> DfgProjectDetails:
logger.debug(f"Received request to get single DFG project for id={id}")
return await projects_service.get_single_dfg_project(
dfg_search_client=dfg_search_client,
return projects_service.get_single_dfg_project(
project_id=id,
)
@@ -153,15 +122,11 @@ async def get_single_dfg_project(
},
response_model_by_alias=False,
)
async def get_single_bund_project(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
def get_single_bund_project(
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
) -> BundProjectDetails:
logger.debug(f"Received request to get single BUND project for id={id}")
return await projects_service.get_single_bund_project(
bund_search_client=bund_search_client,
return projects_service.get_single_bund_project(
project_id=id,
)
@@ -180,10 +145,7 @@ async def get_single_bund_project(
},
response_model_by_alias=False,
)
async def get_institution_bund_projects_funding_over_time(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
def get_institution_bund_projects_funding_over_time(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -191,8 +153,7 @@ async def get_institution_bund_projects_funding_over_time(
str, Query(description="The institution ID to filter by.")
],
) -> InstitutionFunderSummary:
return await projects_service.get_institution_bund_projects_funding_over_time(
bund_search_client=bund_search_client,
return projects_service.get_institution_bund_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -213,7 +174,6 @@ async def get_institution_bund_projects_funding_over_time(
response_model_by_alias=False,
)
async def search_cordis_eu_projects(
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -243,7 +203,6 @@ async def search_cordis_eu_projects(
response_model_by_alias=False,
)
async def get_institution_cordis_eu_projects_funding_over_time(
eu_search_client: Annotated[EuProjectsSearchClient, Depends(get_eu_search_client)],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -252,7 +211,6 @@ async def get_institution_cordis_eu_projects_funding_over_time(
],
) -> InstitutionFunderSummary:
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
eu_search_client=eu_search_client,
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -273,9 +231,6 @@ async def get_institution_cordis_eu_projects_funding_over_time(
response_model_by_alias=False,
)
async def get_dfg_projects(
dfg_search_client: Annotated[
DfgProjectsSearchClient, Depends(get_dfg_search_client)
],
author_id: Annotated[str, Query(description="The author ID to filter by.")],
topic: Annotated[
Optional[str], Query(description="The topic to filter by.")
@@ -297,7 +252,6 @@ async def get_dfg_projects(
sort_direction,
)
return await projects_service.get_dfg_projects_by_author_id(
dfg_search_client=dfg_search_client,
author_id=author_id,
topic=topic,
page=page,
+20 -41
View File
@@ -4,9 +4,6 @@ from typing import Any, Dict, List, Optional, Set
from inse.projects import projects_search_client
from inse.projects.projects_search_client import (
BundProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
get_organization_project_contributions_foo,
)
from inse.projects.model import (
@@ -55,8 +52,7 @@ def search_all_projects(
)
async def search_bund_projects(
bund_search_client: BundProjectsSearchClient,
def search_bund_projects(
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -65,15 +61,17 @@ async def search_bund_projects(
f"Invalid project type: {filtering_properties.project_type}. Expected 'bund'."
)
return await get_bund_projects_by_institution_id(
bund_search_client=bund_search_client,
logger.debug(
f"search_bund_projects called with filtering_properties: {filtering_properties}"
)
return get_bund_projects_by_institution_id(
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
async def get_bund_projects_by_institution_id(
bund_search_client: BundProjectsSearchClient,
def get_bund_projects_by_institution_id(
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -89,9 +87,9 @@ async def get_bund_projects_by_institution_id(
)
)
logger.debug(
f"Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
)
response = await bund_search_client.search_bund_projects(
response = projects_search_client.search_bund_projects(
page=filtering_properties.page,
size=filtering_properties.size,
institution_names=institution_aliases,
@@ -150,7 +148,6 @@ def get_cordis_eu_projects_by_institution_id(
async def get_dfg_projects_by_author_id(
dfg_search_client: DfgProjectsSearchClient,
author_id: str,
topic: Optional[str],
page: int,
@@ -169,7 +166,7 @@ async def get_dfg_projects_by_author_id(
)
logger.debug(f"Found author name for author_id={author_id}: {name}")
response = await dfg_search_client.search_dfg_projects(
response = projects_search_client.search_dfg_projects(
page=page,
size=size,
names=[name],
@@ -181,22 +178,9 @@ async def get_dfg_projects_by_author_id(
async def get_institution_cordis_eu_projects_funding_over_time(
eu_search_client: EuProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
# cordis_eu_project_page = await search_cordis_eu_projects(
# eu_search_client,
# institutions_search_client,
# ProjectsFilteringProperties(
# project_type=ProjectType.EU,
# raw_oa_institution_id=raw_oa_institution_id,
# page=0,
# size=10000,
# ),
# )
institution_aliases = (
institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
@@ -220,8 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
)
async def get_institution_bund_projects_funding_over_time(
bund_search_client: BundProjectsSearchClient,
def get_institution_bund_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
@@ -236,7 +219,7 @@ async def get_institution_bund_projects_funding_over_time(
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
response = await bund_search_client.search_bund_projects(
response = projects_search_client.search_bund_projects(
page=0,
size=10000,
institution_names=institution_aliases,
@@ -319,32 +302,30 @@ def _calculate_funding_over_time(
)
async def get_single_dfg_project(
dfg_search_client: DfgProjectsSearchClient,
def get_single_dfg_project(
project_id: str,
) -> DfgProjectDetails:
logger.debug(f"Fetching single DFG project for id={project_id}")
project = await dfg_search_client.get_dfg_project_by_id(project_id)
project = projects_search_client.get_dfg_project_by_id(project_id)
if not project:
raise NotFoundException(f"DFG project with id {project_id} not found")
return project
async def get_single_bund_project(
bund_search_client: BundProjectsSearchClient,
def get_single_bund_project(
project_id: str,
) -> BundProjectDetails:
logger.debug(f"Fetching single BUND project for id={project_id}")
project = await bund_search_client.get_bund_project_by_id(project_id)
project = projects_search_client.get_bund_project_by_id(project_id)
if not project:
raise NotFoundException(f"BUND project with id {project_id} not found")
return project
def search_cordis_eu_projects_for_author_id(
eu_projects_search_client: EuProjectsSearchClient, raw_oa_author_id: str
raw_oa_author_id: str,
) -> CordisEuProjectPage:
# Direct search not possible -> multi stage search
@@ -356,16 +337,14 @@ def search_cordis_eu_projects_for_author_id(
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
project_ids = eu_projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
logger.debug(
f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}"
)
funding_project_page = (
eu_projects_search_client.get_cordis_eu_projects_by_project_ids(
project_ids=project_ids
)
funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids(
project_ids=project_ids
)
return funding_project_page