Moved all projects search client out of class
This commit is contained in:
@@ -47,7 +47,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
|
||||
|
||||
|
||||
def _index_to_cluster(index: ESIndex) -> ESCluster:
|
||||
def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
"""Determines the Elasticsearch cluster to use based on the specified index.
|
||||
|
||||
Args:
|
||||
@@ -68,18 +68,19 @@ def _index_to_cluster(index: ESIndex) -> ESCluster:
|
||||
}:
|
||||
return ESCluster.NES
|
||||
elif index in {
|
||||
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
ESIndex.PROJECTS_BUND_V1,
|
||||
ESIndex.PROJECTS_DFG_ALL,
|
||||
}:
|
||||
return ESCluster.INSE
|
||||
else:
|
||||
raise ValueError(f"Unknown index: {index!r}")
|
||||
return None
|
||||
|
||||
|
||||
def search(
|
||||
index: ESIndex,
|
||||
query_field: Optional[str] = None,
|
||||
query_value: Optional[str] = None,
|
||||
index: ESIndex | List[ESIndex],
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List] = None,
|
||||
size: Optional[int] = None,
|
||||
@@ -93,8 +94,6 @@ def search(
|
||||
|
||||
Args:
|
||||
index (ElasticsearchIndex): The Elasticsearch index to search.
|
||||
query_field (Optional[str], optional): The field to search in. Defaults to None.
|
||||
query_value (Optional[str], optional): The value to search for. Defaults to None.
|
||||
query (Optional[Dict], optional): The full query body. Defaults to None.
|
||||
source (Optional[List], optional): The fields to include in the response. Defaults to None.
|
||||
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
|
||||
@@ -108,16 +107,35 @@ def search(
|
||||
Dict[str, Any]: The search results.
|
||||
"""
|
||||
|
||||
clusters = set()
|
||||
if isinstance(index, list):
|
||||
for idx in index:
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
else:
|
||||
cluster_for_index = _index_to_cluster(index)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
|
||||
if len(clusters) > 1:
|
||||
raise ValueError(
|
||||
f"All indices in the search request must belong to the same cluster, but found clusters: {clusters}"
|
||||
)
|
||||
elif len(clusters) == 1:
|
||||
cluster = clusters.pop()
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
payload: Dict[str, Any]
|
||||
payload: Dict[str, Any] = {}
|
||||
|
||||
if body is not None:
|
||||
payload = body
|
||||
elif query is not None:
|
||||
payload = {"query": query}
|
||||
else:
|
||||
if query is not None:
|
||||
payload["query"] = query
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if size is not None:
|
||||
@@ -128,19 +146,23 @@ def search(
|
||||
payload["sort"] = sort
|
||||
if track_total_hits:
|
||||
payload["track_total_hits"] = True
|
||||
else:
|
||||
payload = {
|
||||
"query": {
|
||||
"query_string": {"default_field": query_field, "query": query_value}
|
||||
}
|
||||
}
|
||||
|
||||
if len(payload) == 0:
|
||||
raise ValueError(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
|
||||
)
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} with payload: {payload}"
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {payload}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(index)
|
||||
else:
|
||||
index_str = index
|
||||
|
||||
response = client.post(
|
||||
f"{elasticsearch_url}/{index}/_search", json=payload, headers=headers
|
||||
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@@ -59,3 +59,6 @@ class ESIndex(StrEnum):
|
||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
|
||||
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
|
||||
|
||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
@@ -13,6 +13,8 @@ from elasticsearch import ApiError, NotFoundError
|
||||
import hashlib
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.model import ESIndex
|
||||
from .. import config
|
||||
from .. import util
|
||||
from ..integrations import llm
|
||||
@@ -28,6 +30,7 @@ from inse.persons.model import (
|
||||
PersonSearchRequest,
|
||||
CareerMetrics,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
|
||||
@@ -55,20 +58,26 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
def search_persons(
|
||||
author_id: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
include: Optional[set[str]] = None,
|
||||
) -> AuthorsListResponse:
|
||||
if author_id:
|
||||
query_field = "_id"
|
||||
query_value = author_id
|
||||
query_ = {
|
||||
"query_string": {
|
||||
"default_field": "_id",
|
||||
"query": author_id,
|
||||
}
|
||||
}
|
||||
|
||||
elif query:
|
||||
query_field = "display_name"
|
||||
query_value = query
|
||||
query_ = {
|
||||
"query_string": {
|
||||
"default_field": "display_name",
|
||||
"query": query,
|
||||
}
|
||||
}
|
||||
else:
|
||||
return AuthorsListResponse(results=[], meta=Meta(count=0))
|
||||
|
||||
data = elasticsearch.search(
|
||||
index="openalex-authors", query_field=query_field, query_value=query_value
|
||||
)
|
||||
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
|
||||
authors = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
@@ -221,9 +230,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
)
|
||||
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("publication_years", {})
|
||||
.get("buckets", [])
|
||||
response.get("aggregations", {}).get("publication_years", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
publication_years: list[int] = []
|
||||
@@ -237,6 +244,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
|
||||
return publication_years
|
||||
|
||||
|
||||
def _classify_career_stage(active_years: int) -> str:
|
||||
if active_years <= 0:
|
||||
return "unknown"
|
||||
@@ -399,7 +407,6 @@ def get_person_by_id(
|
||||
return CustomAuthorsListResponse(results=[custom_author])
|
||||
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
author_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
|
||||
@@ -8,6 +8,7 @@ from pydantic import BaseModel, Field, field_validator
|
||||
from inse.models.bund_project import BundProject
|
||||
from inse.models.eu_project import EuProject
|
||||
from inse.models.cordis_eu_project import CordisEuProject
|
||||
from inse.model import ESIndex
|
||||
|
||||
|
||||
class ProjectType(StrEnum):
|
||||
@@ -15,6 +16,17 @@ class ProjectType(StrEnum):
|
||||
EU = "eu"
|
||||
DFG = "dfg"
|
||||
|
||||
def to_es_index(self) -> ESIndex:
|
||||
mapping = {
|
||||
self.BUND: ESIndex.PROJECTS_BUND_V1,
|
||||
self.EU: ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
self.DFG: ESIndex.PROJECTS_DFG_ALL,
|
||||
}
|
||||
index = mapping.get(self)
|
||||
if index is None:
|
||||
raise ValueError(f"Unsupported project type: {self}")
|
||||
return index
|
||||
|
||||
|
||||
class ProjectsSortBy(StrEnum):
|
||||
TITLE = "title"
|
||||
@@ -31,6 +43,15 @@ class ProjectsSortBy(StrEnum):
|
||||
}
|
||||
return mapping.get(self, "title.keyword")
|
||||
|
||||
def to_bund_project_sort_field(self) -> str:
|
||||
mapping = {
|
||||
self.TITLE: "Thema.keyword",
|
||||
self.FUNDING_START: "funding_start",
|
||||
self.FUNDING_END: "funding_end",
|
||||
self.FUNDING_AMOUNT: "Fördersumme",
|
||||
}
|
||||
return mapping.get(self, "Thema.keyword")
|
||||
|
||||
|
||||
class SortDirection(StrEnum):
|
||||
ASC = "asc"
|
||||
@@ -151,6 +172,9 @@ class FundingProject(BaseModel):
|
||||
)
|
||||
id: str = Field(description="The unique identifier of the project.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the project.")
|
||||
acronym: Optional[str] = Field(
|
||||
default=None, description="The acronym of the project (if available)."
|
||||
)
|
||||
start_date: Optional[date] = Field(
|
||||
default=None, description="The funding start date of the project."
|
||||
)
|
||||
@@ -227,6 +251,7 @@ class FundingProject(BaseModel):
|
||||
title=source.get("title"),
|
||||
start_date=source.get("funding_start"),
|
||||
end_date=source.get("funding_end"),
|
||||
acronym=source.get("acronym"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -145,16 +145,6 @@ class BundProjectsSearchClient(ProjectsSearchClient):
|
||||
api_key=settings.elasticsearch_inse_api_key,
|
||||
)
|
||||
|
||||
def _bund_projects_sort_by_field(self, sort_by: ProjectsSortBy) -> str:
|
||||
if sort_by == ProjectsSortBy.TITLE:
|
||||
return "Thema.keyword"
|
||||
elif sort_by == ProjectsSortBy.FUNDING_START:
|
||||
return "funding_start"
|
||||
elif sort_by == ProjectsSortBy.FUNDING_END:
|
||||
return "funding_end"
|
||||
elif sort_by == ProjectsSortBy.FUNDING_AMOUNT:
|
||||
return "Fördersumme"
|
||||
|
||||
def _bund_projects_query(
|
||||
self,
|
||||
page: int,
|
||||
@@ -210,7 +200,7 @@ class BundProjectsSearchClient(ProjectsSearchClient):
|
||||
query["query"] = {"match_all": {}}
|
||||
|
||||
query["sort"] = [
|
||||
{self._bund_projects_sort_by_field(sort_by): {"order": sort_direction}}
|
||||
{sort_by.to_bund_project_sort_field(): {"order": sort_direction}}
|
||||
]
|
||||
|
||||
query_str = json.dumps(query, indent=2)
|
||||
@@ -781,112 +771,80 @@ class DfgProjectsSearchClient(ProjectsSearchClient):
|
||||
return None
|
||||
|
||||
|
||||
class CompleteProjectsSearchClient(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="cordis_eu_*_projects,projects_bund_v1,projects_dfg_all",
|
||||
api_key=settings.elasticsearch_inse_api_key,
|
||||
def search_all_projects(
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
):
|
||||
sort_by = projects_filtering_properties.sort_by
|
||||
if sort_by != ProjectsSortBy.TITLE:
|
||||
raise ValueError(
|
||||
"Currently only sorting by title is supported across all project types."
|
||||
)
|
||||
|
||||
def _build_projects_search_body(
|
||||
self,
|
||||
page: int,
|
||||
size: int,
|
||||
title: Optional[str] = None,
|
||||
sort_by: ProjectsSortBy = ProjectsSortBy.TITLE,
|
||||
sort_direction: SortDirection = SortDirection.ASC,
|
||||
) -> Dict[str, Any]:
|
||||
if sort_by != ProjectsSortBy.TITLE:
|
||||
raise ValueError("Currently only sorting by title is supported.")
|
||||
sort_direction = projects_filtering_properties.sort_direction
|
||||
sort = [
|
||||
{
|
||||
"title.keyword": {
|
||||
"order": sort_direction,
|
||||
"missing": "_last",
|
||||
"unmapped_type": "keyword",
|
||||
}
|
||||
},
|
||||
{
|
||||
"Thema.keyword": {
|
||||
"order": sort_direction,
|
||||
"missing": "_last",
|
||||
"unmapped_type": "keyword",
|
||||
}
|
||||
},
|
||||
]
|
||||
|
||||
query: Dict[str, Any] = {
|
||||
"size": size,
|
||||
"from": page * size,
|
||||
"sort": [
|
||||
{
|
||||
"title.keyword": {
|
||||
"order": sort_direction,
|
||||
"missing": "_last",
|
||||
"unmapped_type": "keyword",
|
||||
}
|
||||
},
|
||||
{
|
||||
"Thema.keyword": {
|
||||
"order": sort_direction,
|
||||
"missing": "_last",
|
||||
"unmapped_type": "keyword",
|
||||
}
|
||||
},
|
||||
],
|
||||
query = None
|
||||
|
||||
if (
|
||||
projects_filtering_properties.query
|
||||
and projects_filtering_properties.query.strip() != ""
|
||||
):
|
||||
title_query = projects_filtering_properties.query.strip()
|
||||
wildcard_title = f"*{title_query}*"
|
||||
query = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"wildcard": {
|
||||
"title.keyword": {
|
||||
"value": wildcard_title,
|
||||
"case_insensitive": True,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"Thema.keyword": {
|
||||
"value": wildcard_title,
|
||||
"case_insensitive": True,
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
if title and len(title.strip()) > 0:
|
||||
title = f"*{title.strip()}*"
|
||||
query["query"] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"wildcard": {
|
||||
"title.keyword": {
|
||||
"value": title,
|
||||
"case_insensitive": True,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"wildcard": {
|
||||
"Thema.keyword": {
|
||||
"value": title,
|
||||
"case_insensitive": True,
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
return query
|
||||
|
||||
def _project_type_to_index(self, project_type: ProjectType) -> str:
|
||||
if project_type == ProjectType.BUND:
|
||||
return "projects_bund_v1"
|
||||
elif project_type == ProjectType.EU:
|
||||
return "cordis_eu_*_projects"
|
||||
elif project_type == ProjectType.DFG:
|
||||
return "projects_dfg_all"
|
||||
else:
|
||||
raise ValueError(f"Unsupported project type: {project_type}")
|
||||
|
||||
async def search_projects(
|
||||
self,
|
||||
page: int,
|
||||
size: int,
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
title: Optional[str] = None,
|
||||
sort_by: ProjectsSortBy = ProjectsSortBy.TITLE,
|
||||
sort_direction: SortDirection = SortDirection.ASC,
|
||||
):
|
||||
body = self._build_projects_search_body(
|
||||
page=page,
|
||||
size=size,
|
||||
title=title,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
if not selected_project_types:
|
||||
selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG}
|
||||
index = ",".join(
|
||||
self._project_type_to_index(pt) for pt in selected_project_types
|
||||
)
|
||||
|
||||
projects_response = await self.make_search_request(body, index=index)
|
||||
return _response_to_funding_project_page(projects_response, page, size)
|
||||
if not selected_project_types:
|
||||
selected_project_types = {ProjectType.BUND, ProjectType.EU, ProjectType.DFG}
|
||||
index = [project_type.to_es_index() for project_type in selected_project_types]
|
||||
size = projects_filtering_properties.size
|
||||
page = projects_filtering_properties.page
|
||||
offset = page * size
|
||||
response = elasticsearch.search(
|
||||
index=index,
|
||||
size=size,
|
||||
offset=offset,
|
||||
query=query,
|
||||
sort=sort,
|
||||
)
|
||||
return _response_to_funding_project_page(response=response, page=page, size=size)
|
||||
|
||||
|
||||
def _response_to_funding_project_page(
|
||||
|
||||
@@ -22,7 +22,6 @@ from inse.tags import Tags
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.projects_search_client import (
|
||||
BundProjectsSearchClient,
|
||||
CompleteProjectsSearchClient,
|
||||
DfgProjectsSearchClient,
|
||||
EuProjectsSearchClient,
|
||||
)
|
||||
@@ -51,11 +50,6 @@ def get_dfg_search_client() -> DfgProjectsSearchClient:
|
||||
return DfgProjectsSearchClient()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_complete_projects_search_client() -> CompleteProjectsSearchClient:
|
||||
return CompleteProjectsSearchClient()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/author/{raw_oa_author_id}/eu",
|
||||
summary="Get EU projects for an author.",
|
||||
@@ -326,10 +320,7 @@ async def get_dfg_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
async def search_projects(
|
||||
complete_projects_search_client: Annotated[
|
||||
CompleteProjectsSearchClient, Depends(get_complete_projects_search_client)
|
||||
],
|
||||
def search_projects(
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 10,
|
||||
selected_project_types: Annotated[
|
||||
@@ -348,8 +339,7 @@ async def search_projects(
|
||||
SortDirection, Query(description="The sort direction (asc or desc).")
|
||||
] = SortDirection.ASC,
|
||||
) -> FundingProjectPage:
|
||||
return await projects_service.search_projects(
|
||||
projects_search_client=complete_projects_search_client,
|
||||
return projects_service.search_all_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
selected_project_types=selected_project_types,
|
||||
|
||||
@@ -2,9 +2,9 @@ import datetime
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Set
|
||||
|
||||
from inse.projects import projects_search_client
|
||||
from inse.projects.projects_search_client import (
|
||||
BundProjectsSearchClient,
|
||||
CompleteProjectsSearchClient,
|
||||
DfgProjectsSearchClient,
|
||||
EuProjectsSearchClient,
|
||||
get_organization_project_contributions_foo,
|
||||
@@ -30,11 +30,11 @@ from inse.exceptions import NotFoundException
|
||||
from inse.persons.logic import get_author_name_by_id
|
||||
from inse.works.logic import get_publication_dois_of_author
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def search_projects(
|
||||
projects_search_client: CompleteProjectsSearchClient,
|
||||
def search_all_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: ProjectsSortBy,
|
||||
@@ -42,13 +42,16 @@ async def search_projects(
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> FundingProjectPage:
|
||||
return await projects_search_client.search_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
return projects_search_client.search_all_projects(
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
query=title,
|
||||
),
|
||||
selected_project_types=selected_project_types,
|
||||
title=title,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user