diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index db1f699e..2f9362e3 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -7,23 +7,23 @@ Business logic for persons / authors. import json import logging import time -from typing import Optional - +from typing import Optional, Callable, Any, List +import hashlib import httpx from fastapi import HTTPException from .. import config from .. import util -from ..integrations import elasticsearch from inse.models.author import Author from inse.models.authors_list_response import AuthorsListResponse +from inse import util +from inse.integrations import elasticsearch from inse.models.meta import Meta -from typing import Callable, Any -from . import model - +from inse.persons.query_builder import build_authors_search +from inse.persons.model import CustomAuthor, CustomAuthorsListResponse, PersonSearchRequest logger = logging.getLogger(__name__) - +INDEX_NAME="openalex-authors" def search_persons( author_id: Optional[str] = None, @@ -324,10 +324,26 @@ FILTER_BUILDERS: dict[str, Callable[[Any], dict]] = { } } }, - # "cited_by_count": lambda v: {"range": {"cited_by_count": {"gte": v}}}, + + "topic": lambda v: { + "nested": { + "path": "topics", + "query": { + "bool": { + "must": [ + { + "match_phrase": { + "topics.display_name": v + } + } + ] + } + } + } + }, } -def search_persons_with_filters(req: model.PersonSearchRequest) -> AuthorsListResponse: +def search_persons_with_filters(req: PersonSearchRequest) -> AuthorsListResponse: should_clauses = [] must_clauses = [] @@ -369,4 +385,124 @@ def search_persons_with_filters(req: model.PersonSearchRequest) -> AuthorsListRe return AuthorsListResponse( results=[util.get_persons_data(hit) for hit in hits], meta=Meta(count=total_count, page=req.page_offset), - ) \ No newline at end of file + ) + + +def _enrich_author_data(author_data) -> Optional[CustomAuthor]: + if not author_data: + return None + if not isinstance(author_data, dict): + if hasattr(author_data, 'model_dump'): + author_data = author_data.model_dump() + elif hasattr(author_data, 'to_dict'): + author_data = author_data.to_dict() + else: + return None + author_id = author_data.get("id", "") or "" + + h = int(hashlib.md5(author_id.encode('utf-8')).hexdigest(), 16) + + + # Experimental suitability rating + suitability_score = h % 100 + if suitability_score < 15: + relevance_rating = "Sehr geeignet" + elif suitability_score < 50: + relevance_rating = "Geeignet" + else: + relevance_rating = "Möglich" + + # Resilient sanitization of IDs to protect against model type conflicts (Generated) TODO: multiple code occurrences (e.g. in util.py) => refactor into seperate utility function (if required, after all merges) + ids = author_data.get("ids") + if isinstance(ids, dict): + ids_copy = dict(ids) + for str_field in ["openalex", "orcid", "scopus"]: + val = ids_copy.get(str_field) + if val is not None and not isinstance(val, str): + ids_copy[str_field] = str(val) + author_data["ids"] = ids_copy + + base_author = Author.from_dict(author_data) + if not base_author: + return None + + author = CustomAuthor( + **base_author.model_dump(), + relevance_rating=relevance_rating, + ) + return author + +def advanced_search_persons( + query: Optional[str] = None, + institution_name: Optional[str] = None, + topics: Optional[List[str]] = None, + page: int = 1, + page_size: int = 10, + include: Optional[set[str]] = None, + strict: Optional[bool] = False, +) -> CustomAuthorsListResponse: + try: + query_body = build_authors_search( + query=query, + institution_name=institution_name, + topics=topics, + page=page, + page_size=page_size, + include=include, + strict=strict, + track_total_hits = True + ) + response_dict = elasticsearch.search( + index=INDEX_NAME, + body=query_body, + ) + except httpx.HTTPStatusError as e: + if e.response.status_code == 404: + logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") + return CustomAuthorsListResponse( + results=[], + meta=Meta( + count=0, + page=page, + per_page=page_size + ) + ) + elif e.response.status_code == 400: + logger.error(f"Elasticsearch request error: {str(e)}") + raise HTTPException( + status_code=400, detail=f"Elasticsearch request error: {str(e)}" + ) + else: + logger.error(f"Elasticsearch API error: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Elasticsearch API error: {str(e)}" + ) + except httpx.RequestError as e: + logger.error(f"Elasticsearch connection/request error: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}" + ) + except Exception as e: + logger.error(f"Elasticsearch search failed: {str(e)}") + raise HTTPException( + status_code=500, detail=f"Elasticsearch search failed: {str(e)}" + ) + total_count = response_dict.get("hits",{}).get("total",{}).get("value",0) + hits = response_dict.get("hits", {}).get("hits", []) + total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) + + results = [] + for hit in hits: + raw_data = util.get_persons_data(hit) + custom_author = _enrich_author_data(raw_data) + if custom_author: + results.append(custom_author) + + return CustomAuthorsListResponse( + results=results, + meta=Meta( + count=total_count, + page=page, + per_page=page_size + ) + ) diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py index c7b9f20e..77497957 100644 --- a/service/src/main/inse/persons/model.py +++ b/service/src/main/inse/persons/model.py @@ -5,8 +5,20 @@ Data models for persons / authors. """ from pydantic import BaseModel -from typing import Optional from pydantic import Field +from typing import List, Optional +from inse.models.author import Author +from inse.models.meta import Meta + +from inse.models.group_by_result import GroupByResult + +class CustomAuthor(Author): + relevance_rating: Optional[str] = Field(default=None, description="The relevance suitability rating.") + +class CustomAuthorsListResponse(BaseModel): + meta: Optional[Meta] = None + results: Optional[List[CustomAuthor]] = None + group_by: Optional[List[GroupByResult]] = None class PersonBio(BaseModel): diff --git a/service/src/main/inse/search/query_builder.py b/service/src/main/inse/persons/query_builder.py similarity index 97% rename from service/src/main/inse/search/query_builder.py rename to service/src/main/inse/persons/query_builder.py index e882abcd..21a0e39f 100644 --- a/service/src/main/inse/search/query_builder.py +++ b/service/src/main/inse/persons/query_builder.py @@ -11,6 +11,8 @@ def build_authors_search( page_size: int = 10, include: Optional[Set[str]] = None, strict: Optional[bool] = False, + track_total_hits: Optional[bool] = False + ) -> dict: """ Builds an Elasticsearch search request query body for authors as a dictionary. @@ -142,6 +144,7 @@ def build_authors_search( es_from = (page - 1) * page_size body["from"] = es_from body["size"] = es_size + body["track_total_hits"] = track_total_hits # 5. Sorting if not query: diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 81cb96a0..e9221f5a 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -9,6 +9,7 @@ from typing import Annotated, Optional from fastapi import APIRouter from fastapi import Path from fastapi import Query +from typing import List from . import logic from . import model from inse.models.authors_list_response import AuthorsListResponse @@ -182,4 +183,55 @@ def search_persons_by_institution( tags=["Persons"], ) def search_persons_with_filters(body: model.PersonSearchRequest): - return logic.search_persons_with_filters(body) \ No newline at end of file + return logic.search_persons_with_filters(body) + + +@router.get( + "/persons/search-list", + operation_id="searchPersonsList", + response_model=model.CustomAuthorsListResponse, + summary="Searches for persons with advanced filters (Topic & Institution) and pagination.", + response_model_exclude_none=True, + tags=["Persons"], +) +def search_persons_list( + query: Annotated[ + Optional[str], Query(description="Search query (e.g., Arman AND Arzani)") + ] = None, + institution_name: Annotated[ + Optional[str], Query(alias="institutionName", description="Filter by institution name") + ] = None, + topic: Annotated[ + Optional[List[str]], Query(description="Filter by topic display names") + ] = None, + page: Annotated[ + int, Query(description="Page number (1-indexed)", ge=1) + ] = 1, + page_size: Annotated[ + int, Query(alias="pageSize", description="Results per page", ge=1, le=100) + ] = 10, + include: Annotated[ + Optional[str], + Query( + description="Comma-separated include tags", + example="topics_full,topic_share", + ), + ] = None, + strict: Annotated[ + Optional[bool], Query(description="Strict institution search by target year") + ] = False, +): + include_set = ( + {tag.strip().lower() for tag in include.split(",") if tag.strip()} + if include + else None + ) + return logic.advanced_search_persons( + query=query, + institution_name=institution_name, + topics=topic, + page=page, + page_size=page_size, + include=include_set, + strict=strict, + ) diff --git a/service/src/main/inse/search/__init__.py b/service/src/main/inse/search/__init__.py deleted file mode 100644 index 40a96afc..00000000 --- a/service/src/main/inse/search/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/service/src/main/inse/search/logic.py b/service/src/main/inse/search/logic.py deleted file mode 100644 index 536efb1b..00000000 --- a/service/src/main/inse/search/logic.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: utf-8 -*- -import logging -import hashlib -from typing import List, Optional -import httpx -from fastapi import HTTPException -from inse.search.query_builder import build_authors_search - -from inse import util -from inse.integrations import elasticsearch as es_integration -from inse.models.author import Author -from inse.models.meta import Meta -from inse.search.model import CustomAuthor, CustomAuthorsListResponse - -logger = logging.getLogger(__name__) -INDEX_NAME = "openalex-authors" - -def _enrich_author_data(author_data) -> Optional[CustomAuthor]: - if not author_data: - return None - if not isinstance(author_data, dict): - if hasattr(author_data, 'model_dump'): - author_data = author_data.model_dump() - elif hasattr(author_data, 'to_dict'): - author_data = author_data.to_dict() - else: - return None - author_id = author_data.get("id", "") or "" - - h = int(hashlib.md5(author_id.encode('utf-8')).hexdigest(), 16) - - - # Experimental suitability rating - suitability_score = h % 100 - if suitability_score < 15: - relevance_rating = "Sehr geeignet" - elif suitability_score < 50: - relevance_rating = "Geeignet" - else: - relevance_rating = "Möglich" - - # Resilient sanitization of IDs to protect against model type conflicts (Generated) TODO: multiple code occurrences (e.g. in util.py) => refactor into seperate utility function (if required, after all merges) - ids = author_data.get("ids") - if isinstance(ids, dict): - ids_copy = dict(ids) - for str_field in ["openalex", "orcid", "scopus"]: - val = ids_copy.get(str_field) - if val is not None and not isinstance(val, str): - ids_copy[str_field] = str(val) - author_data["ids"] = ids_copy - - base_author = Author.from_dict(author_data) - if not base_author: - return None - - author = CustomAuthor( - **base_author.model_dump(), - relevance_rating=relevance_rating, - ) - return author - -def advanced_search_persons( - query: Optional[str] = None, - institution_name: Optional[str] = None, - topics: Optional[List[str]] = None, - page: int = 1, - page_size: int = 10, - include: Optional[set[str]] = None, - strict: Optional[bool] = False, -) -> CustomAuthorsListResponse: - try: - query_body = build_authors_search( - query=query, - institution_name=institution_name, - topics=topics, - page=page, - page_size=page_size, - include=include, - strict=strict, - ) - response_dict = es_integration.search( - index=INDEX_NAME, - body=query_body, - ) - except httpx.HTTPStatusError as e: - if e.response.status_code == 404: - logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") - return CustomAuthorsListResponse( - results=[], - meta=Meta( - count=0, - page=page, - per_page=page_size - ) - ) - elif e.response.status_code == 400: - logger.error(f"Elasticsearch request error: {str(e)}") - raise HTTPException( - status_code=400, detail=f"Elasticsearch request error: {str(e)}" - ) - else: - logger.error(f"Elasticsearch API error: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch API error: {str(e)}" - ) - except httpx.RequestError as e: - logger.error(f"Elasticsearch connection/request error: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}" - ) - except Exception as e: - logger.error(f"Elasticsearch search failed: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) - - hits = response_dict.get("hits", {}).get("hits", []) - total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) - - results = [] - for hit in hits: - raw_data = util.get_persons_data(hit) - custom_author = _enrich_author_data(raw_data) - if custom_author: - results.append(custom_author) - - return CustomAuthorsListResponse( - results=results, - meta=Meta( - count=total_count, - page=page, - per_page=page_size - ) - ) diff --git a/service/src/main/inse/search/model.py b/service/src/main/inse/search/model.py deleted file mode 100644 index 6d04a644..00000000 --- a/service/src/main/inse/search/model.py +++ /dev/null @@ -1,14 +0,0 @@ -# -*- coding: utf-8 -*- -from pydantic import BaseModel, Field -from typing import List, Optional -from inse.models.author import Author -from inse.models.meta import Meta -from inse.models.group_by_result import GroupByResult - -class CustomAuthor(Author): - relevance_rating: Optional[str] = Field(default=None, description="The relevance suitability rating.") - -class CustomAuthorsListResponse(BaseModel): - meta: Optional[Meta] = None - results: Optional[List[CustomAuthor]] = None - group_by: Optional[List[GroupByResult]] = None diff --git a/service/src/main/inse/search/service.py b/service/src/main/inse/search/service.py deleted file mode 100644 index 8d6227ce..00000000 --- a/service/src/main/inse/search/service.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -import logging -from typing import Annotated, List, Optional -from fastapi import APIRouter, Query, Depends - -from inse import database -from inse.search import model as search_model -from inse.search import logic - -logger = logging.getLogger(__name__) - -router = APIRouter( - prefix="/api/inse-service", - tags=["Persons Search"], - responses={404: {"description": "Not found"}}, -) - -@router.get( - "/persons/search-list", - operation_id="searchPersonsList", - response_model=search_model.CustomAuthorsListResponse, - summary="Searches for persons with advanced filters (Topic & Institution) and pagination.", - response_model_exclude_none=True, - tags=["Persons"], -) -def search_persons_list( - query: Annotated[ - Optional[str], Query(description="Search query (e.g., Arman AND Arzani)") - ] = None, - institution_name: Annotated[ - Optional[str], Query(alias="institutionName", description="Filter by institution name") - ] = None, - topic: Annotated[ - Optional[List[str]], Query(description="Filter by topic display names") - ] = None, - page: Annotated[ - int, Query(description="Page number (1-indexed)", ge=1) - ] = 1, - page_size: Annotated[ - int, Query(alias="pageSize", description="Results per page", ge=1, le=100) - ] = 10, - include: Annotated[ - Optional[str], - Query( - description="Comma-separated include tags", - example="topics_full,topic_share", - ), - ] = None, - strict: Annotated[ - Optional[bool], Query(description="Strict institution search by target year") - ] = False, -): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) - return logic.advanced_search_persons( - query=query, - institution_name=institution_name, - topics=topic, - page=page, - page_size=page_size, - include=include_set, - strict=strict, - ) diff --git a/webapp/src/app/api/api/persons-search.serviceInterface.ts b/webapp/src/app/api/api/persons-search.serviceInterface.ts index 8221785d..23155580 100644 --- a/webapp/src/app/api/api/persons-search.serviceInterface.ts +++ b/webapp/src/app/api/api/persons-search.serviceInterface.ts @@ -11,7 +11,7 @@ import { HttpHeaders } from '@angular/comm import { Observable } from 'rxjs'; -import { CustomAuthorsListResponse } from '../model/models'; +import { CustomAuthorsListResponse } from '../model/custom-authors-list-response'; import { HTTPValidationError } from '../model/models'; diff --git a/webapp/src/app/api/model/topicCount.ts b/webapp/src/app/api/model/topicCount.ts deleted file mode 100644 index d6c3c481..00000000 --- a/webapp/src/app/api/model/topicCount.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -export interface TopicCount { - /** - * The topic display name. - */ - name: string; - /** - * The number of occurrences. - */ - count?: number; -} - diff --git a/webapp/src/app/api/model/topicsByTime.ts b/webapp/src/app/api/model/topicsByTime.ts deleted file mode 100644 index 0dac04a7..00000000 --- a/webapp/src/app/api/model/topicsByTime.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { TopicsByYear } from './topicsByYear'; - - -export interface TopicsByTime { - /** - * Topics grouped by year. - */ - elements?: Array; - /** - * The number of years. - */ - total?: number; -} - diff --git a/webapp/src/app/api/model/topicsByYear.ts b/webapp/src/app/api/model/topicsByYear.ts deleted file mode 100644 index fded8da0..00000000 --- a/webapp/src/app/api/model/topicsByYear.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Innovation Search Engine API - * - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ -import { TopicCount } from './topicCount'; - - -export interface TopicsByYear { - /** - * The publication year. - */ - year: number; - /** - * The number of works in this year. - */ - publication_count?: number; - /** - * The topics in this year. - */ - topics?: Array; - /** - * The primary topics in this year. - */ - primary_topics?: Array; -} - diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index 883d017d..e3c31b4a 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -4,7 +4,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { combineLatest, distinctUntilChanged, map } from 'rxjs'; -import { TopicCount, TopicsByYear, WorksService } from '../../api'; +import { TopicCount,TopicsByYear } from '../../api'; +import { WorksService } from '../../api'; import { ResearchTimelineComponent, TimelineViewMode, diff --git a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts index acba158a..711c0211 100644 --- a/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts +++ b/webapp/src/app/shared/ui/app-searchbar/app-searchbar.component.ts @@ -46,7 +46,7 @@ export class AppSearchbarComponent { constructor() { const params = new URLSearchParams(window.location.search); - const currentSearch = params.get('search') ?? ''; + const currentSearch = params.get('query') ?? ''; this.searchControl.setValue(currentSearch, { emitEvent: false }); // Autocomplete suggestions @@ -100,7 +100,7 @@ export class AppSearchbarComponent { this.router.url.startsWith('/persons') ? [] : ['/persons'], { relativeTo: this.route, - queryParams: { search: search || null, page: 0 }, + queryParams: { query: search || null, page: 1 }, queryParamsHandling: 'merge', }, );