diff --git a/service/src/main/inse/works/v2/router.py b/service/src/main/inse/works/v2/router.py index 5ad09882..5efc3b81 100644 --- a/service/src/main/inse/works/v2/router.py +++ b/service/src/main/inse/works/v2/router.py @@ -7,8 +7,7 @@ from inse.model import SortDirection from inse.works.v2.model import AuthorWorkPage, WorkSortBy from inse.models.openalex.work_topic import WorkTopic from inse.models.openalex.institution import Institution - - +from inse.works.v2.service import get_works_by_keywords router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2]) @@ -68,6 +67,73 @@ async def get_author_works( sort_order=sort_order, ) +@router.get( + "/keyword/search", + operation_id="getWorksByKeywords", + response_model=AuthorWorkPage, + 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, + 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, + language: Annotated[ + list[str] | None, + Query(description="A list of language codes to filter by."), + ] = None, + page: Annotated[ + int, Query(description="The page number to retrieve. (0-based)", ge=1) + ] = 1, + 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, +) -> AuthorWorkPage: + print(topics, keywords, fuzzy, publication_year, publication_type, institution_ids, topic_ids, language, page, size, sort_by, sort_order) + 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 [], + topic_ids=topic_ids or [], + language=language or [], + page=page, + size=size, + sort_by=sort_by, + sort_order=sort_order) @router.get( "/topics/search", diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 3761d73d..e40967a0 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -1,8 +1,9 @@ import logging from typing import List, Optional, Dict +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 ( AuthorWork, AuthorWorkInstitution, @@ -186,3 +187,127 @@ async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Insti logger.debug(f"Hit source for institution {source.get('id', '')}: {source}") institutions.append(Institution.from_dict(source)) # type: ignore return institutions + + +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."), + keywords: Optional[List[str]] = Query(None, description="Raw keywords to search in title/abstract."), + 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), + page: int = 1, + size: int = 10, + sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR), + sort_order: SortDirection = Query(SortDirection.DESCENDING), +): + # 1. Build the Topic/Keyword Clause + topic_clause = None + if fuzzy and topic_ids: + resolved_ids = topic_ids + if resolved_ids: + topic_clause = { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"terms": {"topics.id": resolved_ids}}}}, + {"terms": {"primary_topic.id": resolved_ids}}, + ], + "minimum_should_match": 1, + } + } + elif topics: + # Fallback to match_phrase if resolution failed + topic_clause = { + "bool": { + "should": [{"match_phrase": {"primary_topic.display_name": t}} for t in topics], + "minimum_should_match": 1, + } + } + elif keywords: + # Raw keyword matching across multiple fields + 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}}, + ], + "minimum_should_match": 1, + } + }) + topic_clause = {"bool": {"must": keyword_clauses}} + + if not topic_clause: + # If no search criteria provided, we might want to return an error or all works. + # For this implementation, we'll return an empty page or a default search. + return AuthorWorkPage(elements=[], total=0, page=page, size=size) + + # 2. Build Filters + must = [topic_clause] + 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({ + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.id": institution_ids}} + } + }) + + # 3. Execute Search + sort = [{sort_by.value: "desc"}] if sort_by != WorkSortBy.TITLE else [{"title.keyword": "asc"}] + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_WORKS_WILDCARD, + source=[ + "id", "title", "type", "publication_year", "language", + "cited_by_count", "authorships.institutions.id", + "authorships.institutions.display_name", "authorships.institutions.country_code", "topics" + ], + query={"bool": {"must": must}}, + size=size, + offset=(page - 1) * size, + sort=sort, + + cluster=ESCluster.NES, + ) + + # 4. Map to Model (Reusing logic from v2 service) + hits_block = response.get("hits", {}) + total = hits_block.get("total", {}).get("value", 0) + hits = hits_block.get("hits", []) + elements = [] + for hit in hits: + source = hit.get("_source", {}) + institutions = {} + for authorship in source.get("authorships", []): + for inst in authorship.get("institutions", []): + i_id = inst.get("id", "") + if i_id not in institutions: + institutions[i_id] = AuthorWorkInstitution( + institution_id=i_id, + institution_name=inst.get("display_name", ""), + institution_country_code=inst.get("country_code", ""), + ) + topics_list = [WorkTopic.from_dict(t) for t in source.get("topics", [])] + elements.append(AuthorWork( + id=source.get("id", ""), + title=source.get("title", ""), + type=source.get("type", ""), + publication_year=source.get("publication_year", 0), + language_code=source.get("language") or "", + institutions=list(institutions.values()), + topics=topics_list, + cited_by_count=source.get("cited_by_count", 0), + )) + + return AuthorWorkPage(elements=elements, total=total, page=page, size=size)