diff --git a/service/src/main/inse/search/logic.py b/service/src/main/inse/search/logic.py index 9108af94..536efb1b 100644 --- a/service/src/main/inse/search/logic.py +++ b/service/src/main/inse/search/logic.py @@ -2,12 +2,12 @@ import logging import hashlib from typing import List, Optional +import httpx from fastapi import HTTPException -from elasticsearch import NotFoundError, RequestError, ApiError from inse.search.query_builder import build_authors_search from inse import util -from inse.logic import es_client +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 @@ -69,9 +69,7 @@ def advanced_search_persons( strict: Optional[bool] = False, ) -> CustomAuthorsListResponse: try: - s = build_authors_search( - using=es_client, - index=INDEX_NAME, + query_body = build_authors_search( query=query, institution_name=institution_name, topics=topics, @@ -80,26 +78,35 @@ def advanced_search_persons( include=include, strict=strict, ) - response = s.execute() - except NotFoundError: - logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.") - return CustomAuthorsListResponse( - results=[], - meta=Meta( - count=0, - page=page, - per_page=page_size + 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 + ) ) - ) - except RequestError as e: - logger.error(f"Elasticsearch request error: {str(e)}") + 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=400, detail=f"Elasticsearch request error: {str(e)}" - ) - except ApiError as e: - logger.error(f"Elasticsearch API error: {str(e)}") - raise HTTPException( - status_code=500, detail=f"Elasticsearch API error: {str(e)}" + status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}" ) except Exception as e: logger.error(f"Elasticsearch search failed: {str(e)}") @@ -107,7 +114,6 @@ def advanced_search_persons( status_code=500, detail=f"Elasticsearch search failed: {str(e)}" ) - response_dict = response.to_dict() hits = response_dict.get("hits", {}).get("hits", []) total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0) diff --git a/service/src/main/inse/search/query_builder.py b/service/src/main/inse/search/query_builder.py index 55da874a..e882abcd 100644 --- a/service/src/main/inse/search/query_builder.py +++ b/service/src/main/inse/search/query_builder.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- from typing import List, Optional, Set, Any -from elasticsearch.dsl import Search, query as dsl_query def build_authors_search( using: Any = None, @@ -12,88 +11,144 @@ def build_authors_search( page_size: int = 10, include: Optional[Set[str]] = None, strict: Optional[bool] = False, -) -> Search: +) -> dict: """ - Builds an Elasticsearch search request for authors using elasticsearch-dsl. + Builds an Elasticsearch search request query body for authors as a dictionary. """ - s = Search(using=using, index=index) - # 1. Build Query Clauses + query_clause = None if query: - # Match original query structure with nested bool should - # "must_clauses.append({"bool": {"should": [...], "minimum_should_match": 1}})" - should_match_phrase = dsl_query.MatchPhrase(display_name={"query": query, "boost": 5}) - should_match_phrase_prefix = dsl_query.MatchPhrasePrefix(display_name={"query": query, "boost": 3}) - should_match_fuzziness = dsl_query.Match(display_name={"query": query, "fuzziness": 1}) + query_clause = { + "bool": { + "should": [ + { + "match_phrase": { + "display_name": { + "query": query, + "boost": 5 + } + } + }, + { + "match_phrase_prefix": { + "display_name": { + "query": query, + "boost": 3 + } + } + }, + { + "match": { + "display_name": { + "query": query, + "fuzziness": 1 + } + } + } + ], + "minimum_should_match": 1 + } + } - query_clause = dsl_query.Bool( - should=[ - should_match_phrase, - should_match_phrase_prefix, - should_match_fuzziness - ], - minimum_should_match=1 - ) - s = s.query(query_clause) - # 2. Build Filters + filter_clauses = [] if institution_name: if strict: from datetime import datetime current_year = datetime.now().year target_year = current_year - 1 - inst_query = dsl_query.MatchPhrase(**{"affiliations.institution.display_name": institution_name}) - year_query = dsl_query.Range(**{"affiliations.years": {"gte": target_year}}) - - s = s.filter( - dsl_query.Nested( - path="affiliations", - query=dsl_query.Bool(filter=[inst_query, year_query]) - ) - ) + filter_clauses.append({ + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + { + "match_phrase": { + "affiliations.institution.display_name": institution_name + } + }, + { + "range": { + "affiliations.years": { + "gte": target_year + } + } + } + ] + } + } + } + }) else: - s = s.filter( - dsl_query.Nested( - path="affiliations", - query=dsl_query.MatchPhrase( - **{"affiliations.institution.display_name": institution_name} - ) - ) - ) + filter_clauses.append({ + "nested": { + "path": "affiliations", + "query": { + "match_phrase": { + "affiliations.institution.display_name": institution_name + } + } + } + }) if topics: for t in topics: if t: - s = s.filter( - dsl_query.Nested( - path="topics", - query=dsl_query.MatchPhrase( - **{"topics.display_name": t} - ) - ) - ) + filter_clauses.append({ + "nested": { + "path": "topics", + "query": { + "match_phrase": { + "topics.display_name": t + } + } + } + }) - # If no query and no filters, default to match_all - if not query and not institution_name and not (topics and any(topics)): - s = s.query(dsl_query.MatchAll()) + # Combine query and filters + body = {} + if query_clause: + if filter_clauses: + body["query"] = { + "bool": { + "must": [query_clause], + "filter": filter_clauses + } + } + else: + body["query"] = query_clause + else: + if filter_clauses: + body["query"] = { + "bool": { + "filter": filter_clauses + } + } + else: + body["query"] = { + "match_all": {} + } # 3. Source Filtering if include: - s = s.source(list(include)) + body["_source"] = list(include) else: - s = s.source(True) + body["_source"] = True # 4. Pagination es_size = page_size es_from = (page - 1) * page_size - s = s[es_from:es_from + es_size] + body["from"] = es_from + body["size"] = es_size # 5. Sorting if not query: - s = s.sort( + body["sort"] = [ {"cited_by_count": {"order": "desc"}}, {"works_count": {"order": "desc"}} - ) + ] + + return body - return s