added funding_end, keywords, topic ids, fuzzy filters
This commit is contained in:
@@ -2,35 +2,12 @@ import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
import urllib
|
||||
from inse.config import get_settings
|
||||
from inse.models.bund_project import BundProject
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
CordisEuProjectPage,
|
||||
DfgProjectPage,
|
||||
DfgProjectSummary,
|
||||
EuOrganizationProjectSummary,
|
||||
EuOrganizationProjectSummaryPage,
|
||||
EuOrganizationShort,
|
||||
EuProjectShort,
|
||||
FundingProject,
|
||||
FundingProjectPage,
|
||||
ProjectType,
|
||||
ProjectsFilteringProperties,
|
||||
ProjectsSortBy,
|
||||
SortDirection,
|
||||
)
|
||||
from collections import defaultdict
|
||||
from inse.projects.eu_cordis_projects_enrichment_client import get_enriched_cordis_project_by_id
|
||||
from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
from inse.models.cordis_eu_project import CordisEuProject
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
|
||||
from typing import Union
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -43,8 +20,7 @@ async def get_dfg_author_names_by_ids(author_ids: List[int]) -> Optional[List[st
|
||||
},
|
||||
"size": len(author_ids),
|
||||
}
|
||||
print(body)
|
||||
data = await elasticsearch.search(index=ESIndex.PROJECTS_DFG_PERSONS, body=body, cluster=ESCluster.INSE)
|
||||
data = await elasticsearch.search(index=ESIndex.DFG_PERSONS, body=body, cluster=ESCluster.INSE)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return []
|
||||
@@ -63,7 +39,7 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option
|
||||
"size": len(institution_ids),
|
||||
}
|
||||
|
||||
data = await elasticsearch.search(index=ESIndex.PROJECTS_DFG_INSTITUTES, body=body, cluster=ESCluster.INSE)
|
||||
data = await elasticsearch.search(index=ESIndex.DFG_INSTITUTES, body=body, cluster=ESCluster.INSE)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return []
|
||||
@@ -71,50 +47,24 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option
|
||||
except Exception as e:
|
||||
logger.exception(f"Error fetching institution names for ids {institution_ids}: {str(e)}")
|
||||
return []
|
||||
|
||||
async def get_person_ids_by_institution_names(
|
||||
institution_names: list[str],
|
||||
|
||||
async def get_person_ids_by_institution_ids(
|
||||
institution_ids: list[int],
|
||||
) -> list[int]:
|
||||
cleaned_names = [
|
||||
name.strip()
|
||||
for name in institution_names
|
||||
if name and name.strip()
|
||||
]
|
||||
|
||||
if not cleaned_names:
|
||||
if not institution_ids:
|
||||
return []
|
||||
|
||||
institution_fields = [
|
||||
"institute_name_de",
|
||||
"institute_name_en",
|
||||
"root_name_de",
|
||||
"root_name_en",
|
||||
]
|
||||
|
||||
should_clauses = []
|
||||
|
||||
for name in cleaned_names:
|
||||
for field in institution_fields:
|
||||
should_clauses.append(
|
||||
{
|
||||
"match_phrase": {
|
||||
field: name
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_PERSONS,
|
||||
index=ESIndex.DFG_PERSONS,
|
||||
cluster=ESCluster.INSE,
|
||||
body={
|
||||
"size": 10000,
|
||||
"_source": ["person_id"],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": should_clauses,
|
||||
"minimum_should_match": 1,
|
||||
"terms": {
|
||||
"institute_id": institution_ids
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -124,4 +74,173 @@ async def get_person_ids_by_institution_names(
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if hit.get("_source", {}).get("person_id") is not None
|
||||
}
|
||||
)
|
||||
)
|
||||
async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
|
||||
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
|
||||
even if the topics are distributed across multiple documents for the same project.
|
||||
"""
|
||||
if not topic_ids:
|
||||
return []
|
||||
|
||||
required_topics = set(topic_ids)
|
||||
|
||||
project_topics: dict[str, Set[str]] = defaultdict(set)
|
||||
|
||||
page_size = 1000
|
||||
from_ = 0
|
||||
|
||||
while True:
|
||||
body = {
|
||||
"size": page_size,
|
||||
"from": from_,
|
||||
"_source": ["project_id", "topic_matches"],
|
||||
"query": {
|
||||
"terms": {
|
||||
"topic_matches.topic_id.keyword": topic_ids
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_TOPICS,
|
||||
cluster=ESCluster.INSE,
|
||||
body=body,
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
source = hit["_source"]
|
||||
|
||||
project_id = source.get("project_id")
|
||||
if not project_id:
|
||||
continue
|
||||
|
||||
topic_matches = source.get("topic_matches") or []
|
||||
|
||||
if isinstance(topic_matches, dict):
|
||||
topic_matches = [topic_matches]
|
||||
|
||||
for match in topic_matches:
|
||||
topic_id = match.get("topic_id")
|
||||
if topic_id in required_topics:
|
||||
project_topics[project_id].add(topic_id)
|
||||
|
||||
if len(hits) < page_size:
|
||||
break
|
||||
|
||||
from_ += page_size
|
||||
|
||||
return [
|
||||
project_id
|
||||
for project_id, found_topics in project_topics.items()
|
||||
if required_topics.issubset(found_topics)
|
||||
]
|
||||
async def get_openalex_topics_for_dfg_projects(
|
||||
project_ids: List[str],
|
||||
) -> Dict[int, List[Dict[str, Any]]]:
|
||||
"""Fetches OpenAlex topic matches for the given DFG project IDs.
|
||||
|
||||
Args:
|
||||
project_ids (List[str]): The DFG project IDs to fetch topics for.
|
||||
|
||||
Returns:
|
||||
Dict[int, List[Dict[str, Any]]]: Mapping of project_id -> list of topic match dicts,
|
||||
each containing topic_id, topic_display_name, domain, field, subfield, rank.
|
||||
"""
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
topic_lookup: Dict[int, List[Dict[str, Any]]] = {}
|
||||
|
||||
page_size = 1000
|
||||
from_ = 0
|
||||
# print(f"Fetching topics for {len(project_ids)} DFG projects in batches of {page_size}...{project_ids}")
|
||||
while True:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_TOPICS,
|
||||
cluster=ESCluster.INSE,
|
||||
body={
|
||||
"size": page_size,
|
||||
"from": from_,
|
||||
"query": {
|
||||
"terms": {
|
||||
"project_id.keyword": project_ids
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
source = hit["_source"]
|
||||
project_id = int(source.get("project_id"))
|
||||
if project_id is None:
|
||||
continue
|
||||
|
||||
topic_matches = source.get("topic_matches") or []
|
||||
if isinstance(topic_matches, dict):
|
||||
topic_matches = [topic_matches]
|
||||
|
||||
topic_lookup.setdefault(project_id, []).extend(topic_matches)
|
||||
|
||||
if len(hits) < page_size:
|
||||
break
|
||||
|
||||
from_ += page_size
|
||||
#logger.info(f"Fetched topics for {len(topic_lookup)} DFG projects.")
|
||||
return topic_lookup
|
||||
|
||||
async def get_person_institutes(
|
||||
person_ids: list[int],
|
||||
) -> dict[str, dict]:
|
||||
|
||||
if not person_ids:
|
||||
return {}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PERSONS,
|
||||
cluster=ESCluster.INSE,
|
||||
body={
|
||||
"size": len(person_ids),
|
||||
"_source": [
|
||||
"person_id",
|
||||
"root_id",
|
||||
"institute_id",
|
||||
"root_name_de",
|
||||
"root_name_en",
|
||||
"institute_name_de",
|
||||
"institute_name_en",
|
||||
"address_country_de",
|
||||
"address_country_en",
|
||||
],
|
||||
"query": {
|
||||
"terms": {
|
||||
"person_id": person_ids,
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
result = {}
|
||||
|
||||
for hit in response["hits"]["hits"]:
|
||||
source = hit["_source"]
|
||||
|
||||
result[source["person_id"]] = {
|
||||
"person_id": source["person_id"],
|
||||
"root_id": source.get("root_id"),
|
||||
"institute_id": source.get("institute_id"),
|
||||
"root_name_de": source.get("root_name_de"),
|
||||
"root_name_en": source.get("root_name_en"),
|
||||
"institute_name_de": source.get("institute_name_de"),
|
||||
"institute_name_en": source.get("institute_name_en"),
|
||||
"address_country_de": source.get("address_country_de"),
|
||||
"address_country_en": source.get("address_country_en"),
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from datetime import date
|
||||
import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List, Optional
|
||||
from typing import List, Optional, Dict, Any
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
@@ -13,6 +13,7 @@ from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H20
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
|
||||
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
|
||||
from typing import Union
|
||||
|
||||
class ProjectType(StrEnum):
|
||||
@@ -24,7 +25,7 @@ class ProjectType(StrEnum):
|
||||
mapping = {
|
||||
self.BUND: ESIndex.PROJECTS_BUND_V1,
|
||||
self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
self.DFG: ESIndex.PROJECTS_DFG_ALL,
|
||||
self.DFG: ESIndex.DFG_PROJECTS,
|
||||
}
|
||||
index = mapping.get(self)
|
||||
if index is None:
|
||||
@@ -155,6 +156,10 @@ class DfgProjectSummary(BaseModel):
|
||||
default=None,
|
||||
description="The subject classifications of the DFG project.",
|
||||
)
|
||||
topics: Optional[List[Topic]] = Field(
|
||||
default=None,
|
||||
description="The topics associated with the DFG project.",
|
||||
)
|
||||
@classmethod
|
||||
def from_hit(cls, hit: dict) -> "DfgProjectSummary":
|
||||
source = hit.get("_source", {})
|
||||
@@ -203,6 +208,16 @@ class DfgProjectSummary(BaseModel):
|
||||
institution=institution,
|
||||
)
|
||||
)
|
||||
topics_raw = source.get("topics") or []
|
||||
topics = None
|
||||
if isinstance(topics_raw, list) and topics_raw:
|
||||
# Sort by rank if present, so the most relevant topic comes first
|
||||
sorted_topics_raw = sorted(
|
||||
(t for t in topics_raw if isinstance(t, dict)),
|
||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||
)
|
||||
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
||||
|
||||
return cls(
|
||||
id=hit.get("_id", ""),
|
||||
link=source.get("link") or source.get("page_url"),
|
||||
@@ -229,9 +244,44 @@ class DfgProjectSummary(BaseModel):
|
||||
institutions=list(institutions.values()),
|
||||
names=names,
|
||||
persons=project_persons,
|
||||
subject_classifications=[DFGProjectFachgebieteInner.from_dict(cls) for cls in source.get('subject_classifications', [])]
|
||||
subject_classifications=[DFGProjectFachgebieteInner.from_dict(cls) for cls in source.get('subject_classifications', [])],
|
||||
topics=topics
|
||||
)
|
||||
@staticmethod
|
||||
def _topic_from_match(match: Dict[str, Any]) -> Topic:
|
||||
"""Builds a (partial) Topic model from a flattened topic_match dict
|
||||
coming from the `projects_dfg_openalex_topics` index.
|
||||
|
||||
Args:
|
||||
match (Dict[str, Any]): A single topic match entry, e.g.:
|
||||
{
|
||||
"rank": 1,
|
||||
"topic_id": "https://openalex.org/T12220",
|
||||
"topic_display_name": "Quantum Electrodynamics and Casimir Effect",
|
||||
"subfield": "Atomic and Molecular Physics, and Optics",
|
||||
"field": "Physics and Astronomy",
|
||||
"domain": "Physical Sciences",
|
||||
"match_score": None
|
||||
}
|
||||
|
||||
Returns:
|
||||
Topic: The constructed Topic instance.
|
||||
"""
|
||||
domain_name = match.get("domain")
|
||||
field_name = match.get("field")
|
||||
subfield_name = match.get("subfield")
|
||||
|
||||
domain = TopicDomain(display_name=domain_name) if domain_name else None
|
||||
field = TopicField(display_name=field_name) if field_name else None
|
||||
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
|
||||
|
||||
return Topic(
|
||||
id=match.get("topic_id"),
|
||||
display_name=match.get("topic_display_name"),
|
||||
domain=domain,
|
||||
field=field,
|
||||
subfield=subfield,
|
||||
)
|
||||
|
||||
class DfgProjectPage(Page):
|
||||
elements: List[DfgProjectSummary] = Field(
|
||||
@@ -371,9 +421,9 @@ class FundingProject(BaseModel):
|
||||
|
||||
@classmethod
|
||||
def from_dfg_projects_hit(cls, hit: dict) -> "FundingProject":
|
||||
if hit.get("_index") != ESIndex.PROJECTS_DFG_ALL.value:
|
||||
if hit.get("_index") != ESIndex.DFG_PROJECTS.value:
|
||||
raise ValueError(
|
||||
f"The provided hit does not belong to the '{ESIndex.PROJECTS_DFG_ALL.value}' index."
|
||||
f"The provided hit does not belong to the '{ESIndex.DFG_PROJECTS.value}' index."
|
||||
)
|
||||
|
||||
source = hit.get("_source", {})
|
||||
|
||||
@@ -30,7 +30,7 @@ from inse.model import ESCluster, ESIndex
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
|
||||
from inse.projects.logic import get_person_ids_by_institution_names
|
||||
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
|
||||
from typing import Union
|
||||
settings = get_settings()
|
||||
|
||||
@@ -577,32 +577,44 @@ async def get_eu_cordis_projects_by_id(
|
||||
project_id=project_id
|
||||
)
|
||||
return enriched_project
|
||||
|
||||
|
||||
# DFG
|
||||
|
||||
|
||||
async def search_dfg_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
institution_names: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[int]] = None,
|
||||
names: Optional[List[str]] = None,
|
||||
topics: Optional[List[str]] = None,
|
||||
keywords: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
filter_topic_ids: Optional[List[str]] = None,
|
||||
title: Optional[str] = None,
|
||||
funding_years: Optional[List[str]] = None,
|
||||
funding_start_years: Optional[List[str]] = None,
|
||||
funding_end_years: Optional[List[str]] = None,
|
||||
sort_by: str = "id",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
) -> 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.
|
||||
institution_names (Optional[List[str]], optional): The list of institution names to filter by. Defaults to None.
|
||||
names (Optional[List[str]], optional): The list of names to search for. Defaults to None.
|
||||
topics (Optional[List[str]], optional): The list of topics to search for. Defaults to None.
|
||||
title (Optional[str], optional): The title to search for. Defaults to None.
|
||||
funding_years (Optional[List[str]], optional): The funding years to filter by. 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".
|
||||
institution_ids (Optional[List[int]], optional): Institution IDs to filter by.
|
||||
names (Optional[List[str]], optional): Names to search for.
|
||||
keywords (Optional[List[str]], optional): Raw keywords to search in title/abstract/subject fields.
|
||||
Only used when `fuzzy=False` (or when no topic_ids are given).
|
||||
topic_ids (Optional[List[str]], optional): Topic IDs to resolve to matching projects.
|
||||
Only used when `fuzzy=True`.
|
||||
filter_topic_ids (Optional[List[str]], optional): Additional topic IDs to filter results by
|
||||
(OR semantics within this list), applied independently of the fuzzy/keyword search mode.
|
||||
title (Optional[str], optional): Title to search for.
|
||||
funding_start_years (Optional[List[str]], optional): Funding start years to filter by.
|
||||
funding_end_years (Optional[List[str]], optional): Funding end years to filter by.
|
||||
sort_by (str, optional): Field to sort by. Defaults to "id".
|
||||
sort_direction (str, optional): Sort direction. Defaults to "asc".
|
||||
fuzzy (bool, optional): If True, use topic_id resolution. If False, use raw keyword
|
||||
phrase-prefix search. Defaults to False.
|
||||
|
||||
Returns:
|
||||
DfgProjectPage: The search results.
|
||||
@@ -631,20 +643,56 @@ async def search_dfg_projects(
|
||||
}
|
||||
|
||||
must_clauses: List[Dict[str, Any]] = []
|
||||
if topics:
|
||||
for topic in topics:
|
||||
if topic.strip() != "":
|
||||
must_clauses.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": topic,
|
||||
"fields": ["title", "title_de", "title_en","abstract_de","abstract_en","subject_area_de","subject_area_en","subject_classifications.fach","subject_classifications.fachkollegium","subject_classifications.fachgebiet,subject_classifications.fachgebiet_de","subject_classifications.wissenschaftsbereich"],
|
||||
"type": "phrase_prefix",
|
||||
"max_expansions": 100,
|
||||
}
|
||||
}
|
||||
|
||||
# === Primary search clause: mutually exclusive fuzzy(topic_ids) vs keyword phrase search ===
|
||||
if fuzzy and topic_ids:
|
||||
matching_project_ids = await get_dfg_project_ids_by_topic_ids(
|
||||
topic_ids=topic_ids
|
||||
)
|
||||
|
||||
if not matching_project_ids:
|
||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||
|
||||
must_clauses.append({"terms": {"id": matching_project_ids}})
|
||||
|
||||
elif keywords:
|
||||
keyword_clauses = []
|
||||
for keyword in keywords:
|
||||
if keyword.strip() == "":
|
||||
continue
|
||||
keyword_clauses.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": keyword,
|
||||
"fields": [
|
||||
"title", "title_de", "title_en",
|
||||
"abstract_de", "abstract_en",
|
||||
"subject_area_de", "subject_area_en",
|
||||
"subject_classifications.fach",
|
||||
"subject_classifications.fachkollegium",
|
||||
"subject_classifications.fachgebiet",
|
||||
"subject_classifications.fachgebiet_de",
|
||||
"subject_classifications.wissenschaftsbereich",
|
||||
],
|
||||
"type": "phrase_prefix",
|
||||
"max_expansions": 100,
|
||||
}
|
||||
}
|
||||
)
|
||||
if keyword_clauses:
|
||||
must_clauses.append({"bool": {"must": keyword_clauses}})
|
||||
|
||||
# === Additional independent filters (applied regardless of fuzzy/keyword mode) ===
|
||||
if filter_topic_ids:
|
||||
matching_filter_project_ids = await get_dfg_project_ids_by_topic_ids(
|
||||
topic_ids=filter_topic_ids
|
||||
)
|
||||
|
||||
if not matching_filter_project_ids:
|
||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||
|
||||
must_clauses.append({"terms": {"id": matching_filter_project_ids}})
|
||||
|
||||
if title:
|
||||
must_clauses.append(
|
||||
{
|
||||
@@ -656,101 +704,66 @@ async def search_dfg_projects(
|
||||
}
|
||||
}
|
||||
)
|
||||
if funding_years:
|
||||
must_clauses.append(
|
||||
{
|
||||
"terms": {
|
||||
"funding_start": funding_years
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if funding_start_years:
|
||||
must_clauses.append({"terms": {"funding_start": funding_start_years}})
|
||||
|
||||
if funding_end_years:
|
||||
must_clauses.append({"terms": {"funding_end": funding_end_years}})
|
||||
|
||||
if names:
|
||||
name_must_clauses = []
|
||||
|
||||
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(
|
||||
{
|
||||
"match": {
|
||||
"persons.full_name": {
|
||||
"query": part,
|
||||
"operator": "and",
|
||||
}
|
||||
match_musts = [
|
||||
{
|
||||
"match": {
|
||||
"persons.full_name": {
|
||||
"query": part,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
for part in name_parts
|
||||
]
|
||||
|
||||
name_must_clauses.append(
|
||||
{
|
||||
"nested": {
|
||||
"path": "persons",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": match_musts
|
||||
}
|
||||
},
|
||||
"query": {"bool": {"must": match_musts}},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if name_must_clauses:
|
||||
must_clauses.append(
|
||||
{
|
||||
"bool": {
|
||||
"must": name_must_clauses
|
||||
}
|
||||
}
|
||||
)
|
||||
must_clauses.append({"bool": {"must": name_must_clauses}})
|
||||
|
||||
|
||||
if institution_names:
|
||||
matching_person_ids = await get_person_ids_by_institution_names(
|
||||
institution_names
|
||||
if institution_ids:
|
||||
matching_person_ids = await get_person_ids_by_institution_ids(
|
||||
institution_ids=institution_ids
|
||||
)
|
||||
|
||||
if not matching_person_ids:
|
||||
return DfgProjectPage(
|
||||
elements=[],
|
||||
total=0,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||
|
||||
must_clauses.append(
|
||||
{
|
||||
"nested": {
|
||||
"path": "persons",
|
||||
"query": {
|
||||
"terms": {
|
||||
"persons.person_id": matching_person_ids
|
||||
}
|
||||
},
|
||||
"query": {"terms": {"persons.person_id": matching_person_ids}},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
body["query"] = (
|
||||
{"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||
)
|
||||
|
||||
if must_clauses:
|
||||
body["query"] = {
|
||||
"bool": {
|
||||
"must": must_clauses
|
||||
}
|
||||
}
|
||||
else:
|
||||
body["query"] = {
|
||||
"match_all": {}
|
||||
}
|
||||
if must_clauses:
|
||||
body["query"] = {"bool": {"must": must_clauses}}
|
||||
else:
|
||||
body["query"] = {"match_all": {}}
|
||||
|
||||
# === Sorting ===
|
||||
sort_by = sort_by.strip().lower()
|
||||
sort_direction = sort_direction.strip().lower()
|
||||
if sort_direction not in ["asc", "desc"]:
|
||||
@@ -758,69 +771,61 @@ async def search_dfg_projects(
|
||||
logger.debug(f"Sorting DFG projects by {sort_by} 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_de.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": {"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": {"order": sort_direction}}
|
||||
elif sort_by == "professional_classification":
|
||||
logger.debug(
|
||||
f"Sorting DFG projects by Fachliche Zuordnung with direction {sort_direction}"
|
||||
)
|
||||
sort_config = {"subject_area_de.keyword": {"order": sort_direction}}
|
||||
else:
|
||||
logger.debug(f"Sorting DFG projects by id with direction {sort_direction}")
|
||||
sort_config = {"id": {"order": sort_direction}}
|
||||
|
||||
body["sort"] = [sort_config]
|
||||
print(body)
|
||||
|
||||
# === Execute Search ===
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
cluster=ESCluster.INSE,
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
project_ids = [hit["_source"]["id"] for hit in hits]
|
||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
||||
|
||||
person_ids = {
|
||||
person["person_id"]
|
||||
for hit in hits
|
||||
for person in hit["_source"].get("persons", [])
|
||||
if person.get("person_id") is not None
|
||||
}
|
||||
person_lookup = await get_person_institutes(person_ids=list(person_ids))
|
||||
|
||||
person_lookup = await get_person_institutes(person_ids = list(person_ids), institution_names=institution_names)
|
||||
for hit in hits:
|
||||
persons = hit["_source"].get("persons", [])
|
||||
source = hit["_source"]
|
||||
project_id = source["id"]
|
||||
|
||||
source["topics"] = topic_lookup.get(project_id, [])
|
||||
|
||||
persons = source.get("persons", [])
|
||||
for person in persons:
|
||||
person_id = person.get("person_id")
|
||||
|
||||
institute = person_lookup.get(person_id)
|
||||
|
||||
if institute:
|
||||
person["root_id"] = institute.get("root_id")
|
||||
person["institute_id"] = institute.get("institute_id")
|
||||
|
||||
person["root_name_de"] = institute.get("root_name_de")
|
||||
person["root_name_en"] = institute.get("root_name_en")
|
||||
|
||||
person["institute_name_de"] = institute.get("institute_name_de")
|
||||
person["institute_name_en"] = institute.get("institute_name_en")
|
||||
person["address_country_de"] = institute.get("address_country_de")
|
||||
person["address_country_en"] = institute.get("address_country_en")
|
||||
|
||||
|
||||
|
||||
return _complete_response_to_dfg_project_page(response, page, size)
|
||||
|
||||
return _complete_response_to_dfg_project_page(response, page, size)
|
||||
|
||||
def _complete_response_to_dfg_project_page(
|
||||
response: dict, page: int, size: int
|
||||
@@ -840,96 +845,6 @@ def _complete_response_to_dfg_project_page(
|
||||
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 get_person_institutes(
|
||||
person_ids: list[int],
|
||||
institution_names: list[str] | None = None,
|
||||
) -> dict[str, dict]:
|
||||
|
||||
if not person_ids:
|
||||
return {}
|
||||
query = {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"terms": {
|
||||
"id": person_ids,
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
if institution_names:
|
||||
query["bool"]["must"].append(
|
||||
{
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"match_phrase": {
|
||||
"institute_name_de": institution_names
|
||||
}
|
||||
},
|
||||
{
|
||||
"match_phrase": {
|
||||
"institute_name_en": institution_names
|
||||
}
|
||||
},
|
||||
{
|
||||
"match_phrase": {
|
||||
"root_name_de": institution_names
|
||||
}
|
||||
},
|
||||
{
|
||||
"match_phrase": {
|
||||
"root_name_en": institution_names
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_PERSONS,
|
||||
cluster=ESCluster.INSE,
|
||||
body={
|
||||
"size": len(person_ids),
|
||||
"_source": [
|
||||
"person_id",
|
||||
"root_id",
|
||||
"institute_id",
|
||||
"root_name_de",
|
||||
"root_name_en",
|
||||
"institute_name_de",
|
||||
"institute_name_en",
|
||||
"address_country_de",
|
||||
"address_country_en",
|
||||
],
|
||||
"query": {
|
||||
"terms": {
|
||||
"person_id": person_ids,
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
result = {}
|
||||
|
||||
for hit in response["hits"]["hits"]:
|
||||
source = hit["_source"]
|
||||
|
||||
result[source["person_id"]] = {
|
||||
"person_id": source["person_id"],
|
||||
"root_id": source.get("root_id"),
|
||||
"institute_id": source.get("institute_id"),
|
||||
"root_name_de": source.get("root_name_de"),
|
||||
"root_name_en": source.get("root_name_en"),
|
||||
"institute_name_de": source.get("institute_name_de"),
|
||||
"institute_name_en": source.get("institute_name_en"),
|
||||
"address_country_de": source.get("address_country_de"),
|
||||
"address_country_en": source.get("address_country_en"),
|
||||
}
|
||||
return result
|
||||
|
||||
async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""Fetches the details of a single DFG project based on its project ID.
|
||||
@@ -943,7 +858,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
query = {"ids": {"values": [project_id]}}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
query=query,
|
||||
size=1,
|
||||
)
|
||||
@@ -1114,7 +1029,7 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject:
|
||||
return FundingProject.from_cordis_projects_hit(hit=hit)
|
||||
elif hit.get("_index") == ESIndex.PROJECTS_BUND_V1.value:
|
||||
return FundingProject.from_bund_projects_hit(hit=hit)
|
||||
elif hit.get("_index") == ESIndex.PROJECTS_DFG_ALL.value:
|
||||
elif hit.get("_index") == ESIndex.DFG_PROJECTS.value:
|
||||
return FundingProject.from_dfg_projects_hit(hit=hit)
|
||||
else:
|
||||
raise ValueError(
|
||||
|
||||
@@ -322,44 +322,71 @@ async def get_dfg_projects(
|
||||
title: Annotated[
|
||||
Optional[str], Query(description="The title to filter by.")
|
||||
] = None,
|
||||
topics: Annotated[
|
||||
Optional[List[str]], Query(description="The topics to filter by.")
|
||||
keywords: Annotated[
|
||||
Optional[List[str]], Query(description="Raw keywords to search in title/abstract/subject fields.")
|
||||
] = None,
|
||||
funding_years: Annotated[Optional[List[str]], Query(description="The funding years to filter by.")] = None,
|
||||
topic_ids: Annotated[
|
||||
Optional[List[str]], Query(description="The openalex topic IDs to filter by.")
|
||||
] = None,
|
||||
filter_topic_ids: Annotated[
|
||||
Optional[List[str]],
|
||||
Query(
|
||||
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
|
||||
"(union with topic_ids). Only used when fuzzy=True."
|
||||
),
|
||||
] = None,
|
||||
funding_start_years: Annotated[Optional[List[str]], Query(description="The funding start years to filter by.")] = None,
|
||||
funding_end_years: Annotated[Optional[List[str]], Query(description="The funding end years to filter by.")] = None,
|
||||
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
|
||||
sort_direction: Annotated[
|
||||
str, Query(description="The sort direction (asc or desc).")
|
||||
] = "asc",
|
||||
|
||||
fuzzy: Annotated[
|
||||
bool,
|
||||
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
|
||||
] = False,
|
||||
|
||||
) -> DfgProjectPage:
|
||||
logger.debug(
|
||||
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, topics=%s, title=%s, funding_years=%s, page=%d, size=%d, sort_by=%s, sort_direction=%s",
|
||||
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
||||
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
||||
"sort_direction=%s, fuzzy=%s",
|
||||
author_id,
|
||||
author_filter_ids,
|
||||
topics,
|
||||
institution_ids,
|
||||
keywords,
|
||||
topic_ids,
|
||||
filter_topic_ids,
|
||||
title,
|
||||
funding_years,
|
||||
funding_start_years,
|
||||
funding_end_years,
|
||||
page,
|
||||
size,
|
||||
sort_by,
|
||||
sort_direction,
|
||||
fuzzy,
|
||||
)
|
||||
return await projects_service.get_dfg_projects_by_author_id(
|
||||
author_id=author_id,
|
||||
author_filter_ids=author_filter_ids,
|
||||
institution_ids=institution_ids,
|
||||
funding_years=funding_years,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
title=title,
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
topic_ids=topic_ids,
|
||||
filter_topic_ids=filter_topic_ids,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
summary="Search projects across all funders.",
|
||||
|
||||
@@ -151,28 +151,37 @@ async def get_dfg_projects_by_author_id(
|
||||
author_id: Optional[str],
|
||||
author_filter_ids: Optional[List[int]],
|
||||
institution_ids: Optional[List[int]],
|
||||
topics: Optional[List[str]],
|
||||
keywords: Optional[List[str]],
|
||||
topic_ids: Optional[List[str]],
|
||||
filter_topic_ids: Optional[List[str]],
|
||||
title: Optional[str],
|
||||
funding_years: Optional[List[str]],
|
||||
funding_start_years: Optional[List[str]],
|
||||
funding_end_years: Optional[List[str]],
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: str = "topic",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
) -> DfgProjectPage:
|
||||
logger.debug(
|
||||
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||
"institution_ids=%s, topics=%s, title=%s, funding_years=%s, "
|
||||
"page=%s, size=%s, sort_by=%s, sort_direction=%s",
|
||||
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
||||
"funding_start_years=%s, funding_end_years=%s, "
|
||||
"page=%s, size=%s, sort_by=%s, sort_direction=%s, fuzzy=%s",
|
||||
author_id,
|
||||
author_filter_ids,
|
||||
institution_ids,
|
||||
topics,
|
||||
keywords,
|
||||
topic_ids,
|
||||
filter_topic_ids,
|
||||
title,
|
||||
funding_years,
|
||||
funding_start_years,
|
||||
funding_end_years,
|
||||
page,
|
||||
size,
|
||||
sort_by,
|
||||
sort_direction,
|
||||
fuzzy,
|
||||
)
|
||||
filter_names = []
|
||||
author_name = (
|
||||
@@ -184,7 +193,7 @@ async def get_dfg_projects_by_author_id(
|
||||
logger.debug("No author name found for author_id=%s", author_id)
|
||||
|
||||
filter_names = (
|
||||
await get_dfg_author_names_by_ids(author_ids = author_filter_ids)
|
||||
await get_dfg_author_names_by_ids(author_ids=author_filter_ids)
|
||||
if author_filter_ids
|
||||
else []
|
||||
)
|
||||
@@ -197,13 +206,7 @@ async def get_dfg_projects_by_author_id(
|
||||
if author_name:
|
||||
filter_names.append(author_name)
|
||||
|
||||
institution_names = (
|
||||
await get_dfg_institution_names_by_ids(institution_ids)
|
||||
if institution_ids
|
||||
else []
|
||||
)
|
||||
|
||||
if institution_ids and not institution_names:
|
||||
if institution_ids:
|
||||
logger.debug(
|
||||
"No institutions found for institution_ids=%s",
|
||||
institution_ids,
|
||||
@@ -213,13 +216,18 @@ async def get_dfg_projects_by_author_id(
|
||||
page=page,
|
||||
size=size,
|
||||
names=filter_names or [],
|
||||
institution_names=institution_names,
|
||||
topics=topics,
|
||||
institution_ids=institution_ids,
|
||||
keywords=keywords,
|
||||
topic_ids=topic_ids,
|
||||
filter_topic_ids=filter_topic_ids,
|
||||
title=title,
|
||||
funding_years=funding_years,
|
||||
funding_start_years=funding_start_years,
|
||||
funding_end_years=funding_end_years,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
)
|
||||
|
||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
|
||||
Reference in New Issue
Block a user