Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/Keyword_search_rework
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good

This commit is contained in:
Kazgatari
2026-07-19 20:27:45 +02:00
57 changed files with 56971 additions and 1952 deletions
+2
View File
@@ -63,6 +63,8 @@ class ESIndex(StrEnum):
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "dfg_projects_2.0"
PROJECTS_DFG_PERSONS = "dfg_persons_2.0"
PROJECTS_DFG_INSTITUTES = "dfg_institutes_2.0"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
+8 -15
View File
@@ -118,7 +118,7 @@ def _parse_patent_id(patent_id: str) -> tuple[str, str]:
async def _search_by_id(
client: AllPatentsSearchClient,
patent_id: str,
filling_date: str | None = None,
title: str | None = None,
) -> list[model.PatentEntry]:
try:
source, number = _parse_patent_id(patent_id)
@@ -126,28 +126,27 @@ async def _search_by_id(
return []
if source == "EPO":
data = await client.search_epo(client.epo_detail_query(number, filling_date))
data = await client.search_epo(client.epo_detail_query(number, title))
return parse_epo_hits(data)
data = await client.search_uspto(client.uspto_detail_query(number, filling_date))
data = await client.search_uspto(client.uspto_detail_query(number))
return parse_uspto_hits(data)
async def _search_by_title(
client: AllPatentsSearchClient,
title: str,
filling_date: str | None = None,
prefix: str | None = None,
) -> list[model.PatentEntry]:
if prefix and prefix.upper() == "US":
data = await client.search_uspto(client.uspto_title_query(title, filling_date))
data = await client.search_uspto(client.uspto_title_query(title))
return parse_uspto_hits(data)
if prefix and prefix.upper() == "EP":
data = await client.search_epo(client.epo_title_query(title, filling_date))
data = await client.search_epo(client.epo_title_query(title))
return parse_epo_hits(data)
epo_data, uspto_data = await asyncio.gather(
client.search_epo(client.epo_title_query(title, filling_date)),
client.search_uspto(client.uspto_title_query(title, filling_date)),
client.search_epo(client.epo_title_query(title)),
client.search_uspto(client.uspto_title_query(title)),
)
return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
@@ -156,29 +155,23 @@ async def get_patent_by_id(
patent_id: str,
prefix: str | None = None,
title: str | None = None,
filling_date: str | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.PatentEntry:
all_patents_client = AllPatentsSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
normalized_filling_date = (
_normalize_patent_date(filling_date) if filling_date else None
)
lookup_id = patent_id
if prefix and not patent_id.upper().startswith(prefix.upper()):
lookup_id = f"{prefix.upper()}{patent_id}"
try:
patents = await _search_by_id(
all_patents_client, lookup_id, normalized_filling_date
all_patents_client, lookup_id,
)
if not patents and title:
patents = await _search_by_title(
all_patents_client,
title,
normalized_filling_date,
prefix,
)
@@ -45,11 +45,9 @@ async def get_patent_by_identifier(
identifier: str,
prefix: str | None = None,
title: str | None = None,
filling_date: str | None = None,
):
return await logic.get_patent_by_id(
patent_id=identifier,
prefix=prefix,
title=title,
filling_date=filling_date,
)
@@ -152,21 +152,28 @@ class AllPatentsSearchClient:
"query": query,
}
def epo_detail_query(self, doc_number: str,filling_date: str | None = None) -> dict[str, Any]:
def epo_detail_query(self, doc_number: str, title: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"wildcard": { #eu cordis patents compatibility
"application_number": {
"value": f"{doc_number}*"
}
}
},
{"term": {"doc_number": doc_number}},
{"term": {"doc_number": self.remove_year(doc_number)}},
{"term": {"application_number": self.remove_year(doc_number)}},
{"term": {"application_number": doc_number}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
if title: #eu cordis patents compatibility
query["bool"]["should"].append(
{"match": {"title_en": title}}
)
query["bool"]["should"].append(
{"match": {"title_de": title}}
)
return {
"size": 1,
"_source": [
@@ -178,21 +185,16 @@ class AllPatentsSearchClient:
"query": query,
}
def uspto_detail_query(self, number: str,filling_date: str | None = None) -> dict[str, Any]:
def uspto_detail_query(self, number: str) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"publication_number": number}},
{"term": {"publication_number": self.remove_year(number)}},
{"term": {"application_number": number}},
{"term": {"application_number": self.remove_year(number)}},
{"term": {"application_number": self.remove_year(number)}}, #eu cordis patents compatibility
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": 1,
"_source": [
@@ -204,7 +206,7 @@ class AllPatentsSearchClient:
"query": query,
}
def epo_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
def epo_title_query(self, title: str) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
@@ -214,9 +216,6 @@ class AllPatentsSearchClient:
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
return {
"size": 1,
"_source": [
@@ -228,16 +227,13 @@ class AllPatentsSearchClient:
"query": query,
}
def uspto_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
def uspto_title_query(self, title: str) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [{"match_phrase": {"title": title}}],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": 1,
"_source": [
+2 -4
View File
@@ -87,18 +87,17 @@ async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
"display_name": hit.get("_source", {}).get("display_name"),
}
async def get_author_name_by_id(author_id: str) -> Optional[str]:
try:
query = {
"_source": ["id", "display_name"],
"query": {
"term": {"id": {"value": f"https://openalex.org/{author_id.upper()}"}}
"terms": {"id": [f"https://openalex.org/{author_id.upper()}"]}
},
"size": 1,
}
data = await elasticsearch.search(index=INDEX_NAME, body=query)
data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, body=query)
hits = data.get("hits", {}).get("hits", [])
if not hits:
return None
@@ -107,7 +106,6 @@ async def get_author_name_by_id(author_id: str) -> Optional[str]:
logger.exception(f"Error fetching author name for id {author_id}: {str(e)}")
return None
async def search_persons(
author_id: Optional[str] = None,
query: Optional[str] = None,
+127
View File
@@ -0,0 +1,127 @@
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 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__)
async def get_dfg_author_names_by_ids(author_ids: List[str]) -> Optional[List[str]]:
try:
body = {
"_source": ["id", "full_name"],
"query": {
"terms": {"id": [author_id for author_id in author_ids]}
},
"size": len(author_ids),
}
print(body)
data = await elasticsearch.search(index=ESIndex.PROJECTS_DFG_PERSONS, body=body, cluster=ESCluster.INSE)
hits = data.get("hits", {}).get("hits", [])
if not hits:
return []
return [hit.get("_source", {}).get("full_name") for hit in hits]
except Exception as e:
logger.exception(f"Error fetching author names for ids {author_ids}: {str(e)}")
return []
async def get_dfg_institution_names_by_ids(institution_ids: List[str]) -> Optional[List[str]]:
try:
body = {
"_source": ["id","institute_name_de","institute_name_en"],
"query": {
"terms": {"id": [institution_id for institution_id in institution_ids]}
},
"size": len(institution_ids),
}
data = await elasticsearch.search(index=ESIndex.PROJECTS_DFG_INSTITUTES, body=body, cluster=ESCluster.INSE)
hits = data.get("hits", {}).get("hits", [])
if not hits:
return []
return [hit.get("_source", {}).get("institute_name_de") or hit.get("_source", {}).get("institute_name_en") for hit in hits]
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],
) -> list[int]:
cleaned_names = [
name.strip()
for name in institution_names
if name and name.strip()
]
if not cleaned_names:
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,
cluster=ESCluster.INSE,
body={
"size": 10000,
"_source": ["person_id"],
"query": {
"bool": {
"should": should_clauses,
"minimum_should_match": 1,
}
},
},
)
return list(
{
hit["_source"]["person_id"]
for hit in response.get("hits", {}).get("hits", [])
if hit.get("_source", {}).get("person_id") is not None
}
)
+121 -20
View File
@@ -84,55 +84,156 @@ class EuProjectPage(Page):
elements: List[EuProject] = Field(
default_factory=list, description="The EU projects on this page."
)
class DfgInstitutionSummary(BaseModel):
id: int
name_de: Optional[str] = None
name_en: Optional[str] = None
class DfgPersonSummary(BaseModel):
person_id: int
project_ref_id: int
full_name: Optional[str] = None
role_label_en: Optional[str] = None,
role_label_de: Optional[str] = None,
root_institution: Optional[DfgInstitutionSummary] = None,
institution: Optional[DfgInstitutionSummary] = None
class DfgProjectSummary(BaseModel):
id: str = Field(description="The unique identifier of the DFG project.")
id: str = Field(
description="The unique identifier of the DFG project."
)
link: Optional[str] = Field(
default=None, description="The link to the DFG project details."
default=None,
description="The link to the DFG project details."
)
title: Optional[str] = Field(
default=None, description="The title of the DFG project."
default=None,
description="The title of the DFG project."
)
professional_classification: Optional[str] = Field(
default=None, description="The professional classification of the DFG project."
default=None,
description="The professional classification of the DFG project."
)
funding_start: Optional[str] = Field(
default=None, description="The funding start date of the DFG project."
default=None,
description="The funding start date of the DFG project."
)
funding_end: Optional[str] = Field(
default=None, description="The funding end date of the DFG project."
default=None,
description="The funding end date of the DFG project."
)
root_institutions: List[DfgInstitutionSummary] = Field(
default_factory=list,
description=(
"Root institutions associated with the project "
"(e.g. universities or umbrella organizations)."
),
)
institutions: List[DfgInstitutionSummary] = Field(
default_factory=list,
description="Institutions associated with the project."
)
names: List[str] = Field(
default_factory=list,
description="The names of the researchers involved in the DFG project.",
description="The names of the persons involved in the DFG project.",
)
persons: List[DfgPersonSummary] = Field(
default_factory=list,
description="The persons involved in the DFG project.",
)
@classmethod
def from_hit(cls, hit: dict) -> "DfgProjectSummary":
source = hit.get("_source", {})
fields = hit.get("fields", {})
# Extract names from nested persons array
names = []
institutions = {}
root_institutions = {}
project_persons = []
persons = source.get("persons", [])
if isinstance(persons, list):
for p in persons:
if isinstance(p, dict):
full_name = p.get("full_name")
if full_name:
names.append(full_name.strip())
if not names:
names = fields.get("all_found_names", [])
for person in persons:
if not isinstance(person, dict):
continue
full_name = person.get("full_name")
if full_name:
names.append(full_name.strip())
institution = None
if person.get("institute_id") is not None:
institution = DfgInstitutionSummary(
id=person["institute_id"],
name_de=person.get("institute_name_de"),
name_en=person.get("institute_name_en"),
)
institutions[person["institute_id"]] = institution
root_institution = None
if person.get("root_id") is not None:
root_institution = DfgInstitutionSummary(
id=person["root_id"],
name_de=person.get("root_name_de"),
name_en=person.get("root_name_en"),
)
root_institutions[person["root_id"]] = root_institution
if person.get("person_id") is not None:
project_persons.append(
DfgPersonSummary(
person_id=person["person_id"],
project_ref_id=person.get("project_ref_id"),
full_name=full_name,
role_label_en=person.get("role_label_en"),
role_label_de=person.get("role_label_de"),
root_institution=root_institution,
institution=institution,
)
)
return cls(
id=hit.get("_id", ""),
link=source.get("link") or source.get("page_url"),
title=source.get("title") or source.get("title_de") or source.get("title_en"),
professional_classification=source.get("Fachliche Zuordnung") or source.get("subject_area_de") or source.get("subject_area_en"),
funding_start=str(source.get("funding_start")) if source.get("funding_start") is not None else None,
funding_end=str(source.get("funding_end")) if source.get("funding_end") is not None else None,
title=(
source.get("title")
or source.get("title_de")
or source.get("title_en")
),
professional_classification=(
source.get("Fachliche Zuordnung")
or source.get("subject_area_de")
or source.get("subject_area_en")
),
funding_start=(
str(source.get("funding_start"))
if source.get("funding_start") is not None
else None
),
funding_end=(
str(source.get("funding_end"))
if source.get("funding_end") is not None
else None
),
root_institutions=list(root_institutions.values()),
institutions=list(institutions.values()),
names=names,
persons=project_persons,
)
@@ -30,6 +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 typing import Union
settings = get_settings()
@@ -582,8 +583,11 @@ async def get_eu_cordis_projects_by_id(
async def search_dfg_projects(
page: int,
size: int,
institution_names: Optional[List[str]] = None,
names: Optional[List[str]] = None,
topic: Optional[str] = None,
topics: Optional[List[str]] = None,
title: Optional[str] = None,
funding_years: Optional[List[str]] = None,
sort_by: str = "id",
sort_direction: str = "asc",
) -> DfgProjectPage:
@@ -592,8 +596,11 @@ async def search_dfg_projects(
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.
topic (Optional[str], optional): The topic 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".
@@ -623,53 +630,121 @@ async def search_dfg_projects(
}
must_clauses: List[Dict[str, Any]] = []
if topic is not None and topic.strip() != "":
must_clauses.append(
{
"multi_match": {
"query": topic,
"fields": ["title", "title_de", "title_en"],
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"],
"type": "phrase_prefix",
"max_expansions": 100,
}
}
)
if title:
must_clauses.append(
{
"multi_match": {
"query": title,
"fields": ["title", "title_de", "title_en"],
"type": "phrase_prefix",
"max_expansions": 100,
}
}
)
if funding_years:
must_clauses.append(
{
"terms": {
"funding_start": funding_years
}
}
)
if names:
name_should_clauses = []
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.append(
{
"match": {
"persons.full_name": {
"query": part,
"operator": "and",
}
}
}
})
)
name_should_clauses.append({
name_must_clauses.append(
{
"nested": {
"path": "persons",
"query": {
"bool": {
"must": match_musts
}
},
}
}
)
if 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 not matching_person_ids:
return DfgProjectPage(
elements=[],
total=0,
page=page,
size=size,
)
must_clauses.append(
{
"nested": {
"path": "persons",
"query": {
"bool": {
"must": match_musts
"terms": {
"persons.person_id": matching_person_ids
}
}
},
}
})
}
)
if name_should_clauses:
must_clauses.append(
{"bool": {"should": name_should_clauses, "minimum_should_match": 1}}
)
if must_clauses:
body["query"] = {
"bool": {
"must": must_clauses
}
}
else:
body["query"] = {
"match_all": {}
}
if must_clauses:
body["query"] = {"bool": {"must": must_clauses}}
else:
@@ -704,11 +779,40 @@ async def search_dfg_projects(
sort_config = {"id": {"order": sort_direction}}
body["sort"] = [sort_config]
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
body=body,
cluster=ESCluster.INSE
)
hits = response.get("hits", {}).get("hits", [])
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), institution_names=institution_names)
for hit in hits:
persons = hit["_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")
return _complete_response_to_dfg_project_page(response, page, size)
@@ -730,6 +834,92 @@ 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",
],
"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"),
}
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.
+24 -8
View File
@@ -1,5 +1,5 @@
import logging
from typing import Annotated, Optional, Set
from typing import Annotated, Optional, Set, List
from fastapi import APIRouter, Body, Depends, Path, Query, status
@@ -314,21 +314,33 @@ async def get_institution_cordis_eu_projects_funding_over_time(
response_model_by_alias=False,
)
async def get_dfg_projects(
author_id: Annotated[str, Query(description="The author ID to filter by.")],
topic: Annotated[
Optional[str], Query(description="The topic to filter by.")
author_id: Annotated[Optional[str], Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[Optional[List[str]], Query(description="The author IDs to filter by.")] = None,
institution_ids: Annotated[
Optional[List[str]], Query(description="The institution IDs to filter by.")
] = None,
title: Annotated[
Optional[str], Query(description="The title to filter by.")
] = None,
topics: Annotated[
Optional[List[str]], Query(description="The topics to filter by.")
] = None,
funding_years: Annotated[Optional[List[str]], Query(description="The funding 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.")] = "topic",
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",
) -> DfgProjectPage:
logger.debug(
"Received request to get DFG projects for author_id=%s, topic=%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, topics=%s, title=%s, funding_years=%s, page=%d, size=%d, sort_by=%s, sort_direction=%s",
author_id,
topic,
author_filter_ids,
topics,
title,
funding_years,
page,
size,
sort_by,
@@ -336,7 +348,11 @@ async def get_dfg_projects(
)
return await projects_service.get_dfg_projects_by_author_id(
author_id=author_id,
topic=topic,
author_filter_ids=author_filter_ids,
institution_ids=institution_ids,
funding_years=funding_years,
title=title,
topics=topics,
page=page,
size=size,
sort_by=sort_by,
+60 -17
View File
@@ -26,6 +26,7 @@ from inse.institutions.institutions_search_client import (
)
from inse.exceptions import NotFoundException
from inse.persons.logic import get_author_name_by_id
from inse.projects.logic import get_dfg_author_names_by_ids, get_dfg_institution_names_by_ids
from inse.works.logic import get_publication_dois_of_author
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
@@ -146,37 +147,79 @@ async def get_cordis_eu_projects_by_institution_id(
return page
async def get_dfg_projects_by_author_id(
author_id: str,
topic: Optional[str],
author_id: Optional[str],
author_filter_ids: Optional[List[str]],
institution_ids: Optional[List[str]],
topics: Optional[List[str]],
title: Optional[str],
funding_years: Optional[List[str]],
page: int,
size: int,
sort_by: str = "topic",
sort_direction: str = "asc",
) -> DfgProjectPage:
logger.debug(
f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}"
"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",
author_id,
author_filter_ids,
institution_ids,
topics,
title,
funding_years,
page,
size,
sort_by,
sort_direction,
)
name = await get_author_name_by_id(author_id)
if not name:
logger.debug(f"No author name found for author_id={author_id}")
raise NotFoundException(
f"Display name for author with id {author_id} not found"
)
logger.debug(f"Found author name for author_id={author_id}: {name}")
filter_names = []
author_name = (
await get_author_name_by_id(author_id)
if author_id
else None
)
if author_id and not author_name:
logger.debug("No author name found for author_id=%s", author_id)
response = await projects_search_client.search_dfg_projects(
filter_names = (
await get_dfg_author_names_by_ids(author_ids = author_filter_ids)
if author_filter_ids
else []
)
if author_filter_ids and not filter_names:
logger.debug(
"No author names found for author_filter_ids=%s",
author_filter_ids,
)
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:
logger.debug(
"No institutions found for institution_ids=%s",
institution_ids,
)
return await projects_search_client.search_dfg_projects(
page=page,
size=size,
names=[name],
topic=topic,
names=filter_names or [],
institution_names=institution_names,
topics=topics,
title=title,
funding_years=funding_years,
sort_by=sort_by,
sort_direction=sort_direction,
)
return response
async def get_institution_cordis_eu_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
+45 -2
View File
@@ -14,7 +14,7 @@ from inse.works.v2.model import (
)
from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.works.v2.service import get_works_by_keywords
WORKS_v2_PREFIX = "/api/v2/works"
logger = logging.getLogger(__name__)
@@ -83,7 +83,50 @@ async def get_author_works(
sort_order=sort_order,
)
@router.get(
"/keyword/search",
operation_id="getWorksByKeywords",
response_model=WorkPageV2,
summary="Search works by topics or raw keywords with filters."
)
async def search_works_by_keywords(
topics: Annotated[list[str] | None, Query(description="List of topics to match.")] = None,
topic_ids: Annotated[list[str] | None, Query(description="List of topic IDs to match.")] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(description="Additional topic IDs to filter results by, independent of search mode."),
] = None,
keywords: Annotated[list[str] | None, Query(description="Raw keywords to search in title/abstract.")] = None,
fuzzy: Annotated[bool, Query(description="Use topic resolution if True, otherwise use raw keywords.")] = True,
publication_year: Annotated[list[int] | None, Query(description="A list of publication years to filter by.")] = None,
publication_type: Annotated[list[str] | None, Query(description="A list of publication types to filter by.")] = None,
institution_ids: Annotated[list[str] | None, Query(description="A list of institution IDs to filter by.")] = None,
author_ids: Annotated[list[str] | None, Query(description="A list of author IDs to filter by.")] = None,
language: Annotated[list[str] | None, Query(description="A list of language codes to filter by.")] = None,
title: Annotated[str | None, Query(description="Title to search for in works.")] = None,
page: Annotated[int, Query(description="The page number to retrieve. (0-based)", ge=0)] = 0,
size: Annotated[int, Query(description="The number of works to retrieve per page.", ge=1, le=100)] = 10,
sort_by: Annotated[WorkSortBy, Query(description="The field to sort by.")] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[SortDirection, Query(description="The order to sort by.")] = SortDirection.DESCENDING,
) -> WorkPageV2:
return await get_works_by_keywords(
topics=topics or [],
keywords=keywords or [],
fuzzy=fuzzy,
publication_year=publication_year or [],
publication_type=publication_type or [],
institution_ids=institution_ids or [],
author_ids=author_ids or [],
topic_ids=topic_ids or [],
filter_topic_ids=filter_topic_ids or [],
language=language or [],
title=title,
page=page,
size=size,
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/institution/{raw_oa_institution_id}",
operation_id="getInstitutionWorkPage",
+147 -2
View File
@@ -1,8 +1,8 @@
import logging
from typing import Dict, List, Optional
from fastapi import Query
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
from inse.model import ESIndex, SortDirection, ESCluster
from inse.works.v2.model import (
WorkClassification,
WorkClassificationPage,
@@ -229,6 +229,151 @@ async def get_works(
return await _execute_works_search(must, page, size, sort_by, sort_order)
async def get_works_by_keywords(
topics: Optional[List[str]] = Query(None, description="List of topics to match."),
topic_ids: Optional[List[str]] = Query(None, description="List of topic IDs to match."),
filter_topic_ids: Optional[List[str]] = Query(
None,
description="Additional topic IDs to filter results by (OR semantics), "
"applied independently of the fuzzy/keyword search mode.",
),
keywords: Optional[List[str]] = Query(None, description="Raw keywords to search in title/abstract."),
title: Optional[str] = None,
fuzzy: bool = Query(True, description="Use topic resolution if True, otherwise use raw keywords."),
publication_year: Optional[List[int]] = Query(None),
publication_type: Optional[List[str]] = Query(None, alias="type"),
language: Optional[List[str]] = Query(None),
institution_ids: Optional[List[str]] = Query(None),
author_ids: Optional[List[str]] = Query(None),
page: int = 0,
size: int = 10,
sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR),
sort_order: SortDirection = Query(SortDirection.DESCENDING),
) -> WorkPageV2:
#print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}")
def _topics_nested_clause(should_clauses: List[Dict]) -> Dict:
return {
"nested": {
"path": "topics",
"query": {
"bool": {
"should": should_clauses,
"minimum_should_match": 1,
}
},
"score_mode": "max",
}
}
def _single_topic_id_match(topic_id: str) -> Dict:
return {
"bool": {
"should": [
_topics_nested_clause([{"term": {"topics.id": topic_id}}]),
{"term": {"primary_topic.id": topic_id}},
],
"minimum_should_match": 1,
}
}
topic_clause = None
if fuzzy and topic_ids:
filter_on_ids = list(set(topic_ids + filter_topic_ids))
topic_clause = {
"bool": {"must": [_single_topic_id_match(tid) for tid in filter_on_ids]}
}
elif keywords:
keyword_clauses = []
for kw in keywords:
keyword_clauses.append({
"bool": {
"should": [
{"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw}}}},
{"match_phrase": {"primary_topic.display_name": kw}},
{"match_phrase": {"title": kw}},
{"match_phrase": {"abstract": kw}},
_topics_nested_clause([
{"match_phrase": {"topics.display_name": kw}},
{"match_phrase": {"topics.field.display_name": kw}},
{"match_phrase": {"topics.subfield.display_name": kw}},
{"match_phrase": {"topics.domain.display_name": kw}},
]),
],
"minimum_should_match": 1,
}
})
topic_clause = {"bool": {"must": keyword_clauses}}
if not topic_clause:
return WorkPageV2(elements=[], total=0, page=page, size=size)
#filters
must = [topic_clause]
if title:
must.append(_title_query(title))
if publication_year:
must.append({"terms": {"publication_year": publication_year}})
if publication_type:
must.append({"terms": {"type": publication_type}})
if language:
must.append({"terms": {"language": language}})
if institution_ids:
must.append(_institutions_nested_query(institution_ids))
if author_ids:
must.append(_authors_nested_query(author_ids))
#sorting
if sort_by == WorkSortBy.TITLE:
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
print(f"Final query:",must)
#search
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=[
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"abstract",
"keywords",
"primary_topic",
"authorships.author",
"authorships.institutions.id",
"authorships.institutions.display_name",
"authorships.institutions.country_code",
"topics",
],
query={"bool": {"must": must}},
size=size,
track_total_hits=True,
offset=page * size,
sort=sort,
cluster=ESCluster.NES,
)
print(f"Elasticsearch response: {response}")
logger.debug(f"Query: {{'bool': {{'must': {must}}}}}")
#model mapping
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
hits = hits_block.get("hits", [])
elements: List[Work] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for keyword search: {source}")
work = Work.from_dict(source) # type: ignore
if work is not None:
elements.append(work)
return WorkPageV2(elements=elements, total=total, page=page, size=size)
async def get_author_works(
raw_oa_author_id: str,