From 8515a01ff4aaa16653122161750b00355eaafb1a Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 15 Jun 2026 19:04:44 +0200 Subject: [PATCH] fixed institutuin autocompletion logic, used existing elastic wrapper for queries --- .../institutions_search_client.py | 223 ++++++++++++------ service/src/main/inse/institutions/logic.py | 40 ++-- service/src/main/inse/institutions/service.py | 15 +- .../src/main/inse/institutions/test_logic.py | 58 ----- .../main/inse/models/openalex/institution.py | 11 +- 5 files changed, 171 insertions(+), 176 deletions(-) diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py index 23a736af..dd895930 100644 --- a/service/src/main/inse/institutions/institutions_search_client.py +++ b/service/src/main/inse/institutions/institutions_search_client.py @@ -1,79 +1,73 @@ import logging from typing import List, Set -import httpx - from inse.models.openalex.institution import Institution from inse.exceptions import NotFoundException +from inse.integrations import elasticsearch logger = logging.getLogger(__name__) class InstitutionsSearchClient: - def __init__( - self, - base_url: str, - api_key: str, - ): - self.base_url = base_url - self.api_key = api_key - self.headers = { - "Content-Type": "application/json", - "Authorization": f"ApiKey {self.api_key}", - } + def __init__(self): + """ + Initializes the client. Credentials and URLs are handled by the + centralized elasticsearch integration. + """ + pass async def get_institution_by_id(self, raw_institution_id: str) -> Institution: + """ + Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster. + """ query = { - "query": { - "match": { - "id": f"https://openalex.org/{raw_institution_id.upper()}", - } - }, - "size": 1, + "match": { + "id": f"https://openalex.org/{raw_institution_id.upper()}", + } } + + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=1 + ) + + hits = res.get("hits", {}).get("hits", []) + if not hits: + raise NotFoundException(f"Institution with ID '{raw_institution_id}' not found.") + authors = await self.get_authors_by_institution_id(raw_institution_id) logger.debug( "Retrieved authors for institution_id=%s: %s", raw_institution_id, authors ) - - async with httpx.AsyncClient() as client: - response = await client.post( - f"{self.base_url}/openalex-institutions/_search", - json=query, - headers=self.headers, - ) - response.raise_for_status() - hits = response.json().get("hits", {}).get("hits", []) - if not hits: - raise NotFoundException( - f"Institution with ID '{raw_institution_id}' not found." - ) - - return Institution.from_dict(hits[0]["_source"]) + + return Institution.from_dict(hits[0]["_source"]) async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]: + """ + Fetches authors associated with an institution. + Note: This query is specifically looking for current affiliations (2026). + """ query = { - "query": { - "nested": { - "path": "affiliations", - "query": { - "bool": { - "must": [ - { - "term": { - "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" - } - }, - { - "range": { - "affiliations.years": {"gte": 2026, "lte": 2026} - } - }, - ] - } - }, - } + "nested": { + "path": "affiliations", + "query": { + "bool": { + "must": [ + { + "term": { + "affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}" + } + }, + { + "range": { + "affiliations.years": {"gte": 2026, "lte": 2026} + } + }, + ] + } + }, } } logger.debug( @@ -81,30 +75,103 @@ class InstitutionsSearchClient: raw_institution_id, query, ) - async with httpx.AsyncClient() as client: - response = await client.post( - "https://project.nes.uni-due.de/elastic/openalex-authors/_search", - json=query, - headers=self.headers, - ) - try: - response.raise_for_status() - except httpx.HTTPStatusError as e: - logger.exception( - "Error fetching authors for institution_id=%s: %s, response content: %s", - raw_institution_id, - str(e), - response.text, - ) - return [] - hits = response.json().get("hits", {}).get("hits", []) - authors = set() - for hit in hits: - authors.update( - auth["author"]["display_name"] - for auth in hit["_source"].get("authorships", []) - ) - return list(authors) + + res = elasticsearch.search(index="openalex-authors", query=query) + hits = res.get("hits", {}).get("hits", []) + + # Extracting display_name directly from the author document source + authors = {hit["_source"].get("display_name") for hit in hits if hit["_source"].get("display_name")} + return list(authors) + async def search_institutions( + self, + query_text: str, + country_code: str | None = None, + institution_type: str | None = None, + limit: int = 10, + ) -> list[Institution]: + """ + Autocomplete search for institutions using multi_match on search_as_you_type fields. + Falls back to fuzzy match for typo tolerance on longer queries. + """ + must = [] + + if query_text: + stripped = query_text.strip() + + must.append({ + "bool": { + "should": [ + # Fast prefix matching via search_as_you_type shingles + { + "multi_match": { + "query": stripped, + "type": "bool_prefix", + "fields": [ + "display_name.search", + "display_name.search._2gram", + "display_name.search._3gram", + "display_name_alternatives.search", + "display_name_alternatives.search._2gram", + ], + "boost": 2, + } + }, + # Exact acronym match — high confidence signal + { + "term": { + "display_name_acronyms.keyword": { + "value": stripped.upper(), + "boost": 10, + } + } + }, + # Fuzzy fallback for typos (only worth it for longer input) + *( + [{ + "match": { + "display_name": { + "query": stripped, + "fuzziness": "AUTO", + "boost": 1, + } + } + }] + if len(stripped) >= 4 else [] + ), + ], + "minimum_should_match": 1, + } + }) + + filter_queries = [] + + if country_code: + filter_queries.append({"term": {"country_code": country_code.upper()}}) + + if institution_type: + filter_queries.append({"term": {"type": institution_type}}) + + query = { + "bool": { + "must": must, + "filter": filter_queries, + } + } + + res = elasticsearch.search( + index="openalex-institutions", + query=query, + size=limit, + # Blend relevance score with works_count popularity signal + sort=[ + {"works_count": {"order": "desc"}}, + ], + source=["id", "display_name", "country_code", "type", "works_count", "cited_by_count", "geo"], + ) + + hits = res.get("hits", {}).get("hits", []) + + return [Institution.from_dict(hit["_source"]) for hit in hits] async def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]: """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases. diff --git a/service/src/main/inse/institutions/logic.py b/service/src/main/inse/institutions/logic.py index a4f834ee..7562672e 100644 --- a/service/src/main/inse/institutions/logic.py +++ b/service/src/main/inse/institutions/logic.py @@ -114,34 +114,29 @@ async def autocomplete_institutions( country_code: str | None = None, institution_type: str | None = None, limit: int = 10, - client: OpenAlexInstitutionsClient | None = None, + client: InstitutionsSearchClient, ) -> AutocompleteResponse: - filters = [] - if country_code: - filters.append(f"country_code:{country_code}") - if institution_type: - filters.append(f"type:{institution_type}") - - response = await list_institutions( - search=query, - filter=",".join(filters) if filters else None, - sort="works_count:desc", - per_page=limit, - page=1, - select=("id,ror,display_name,country_code,type,works_count,cited_by_count,geo"), - client=client, + """ + Returns institution options for autocomplete inputs using the local + Elasticsearch cluster via the provided client. + """ + institutions = await client.search_institutions( + query_text=query, + country_code=country_code, + institution_type=institution_type, + limit=limit, ) results = [] - for institution in response.results or []: + for institution in institutions: if not institution.id or not institution.display_name: continue hint_parts = [] - if institution.geo: - if institution.geo.city: + if hasattr(institution, "geo") and institution.geo: + if hasattr(institution.geo, "city") and institution.geo.city: hint_parts.append(institution.geo.city) - if institution.geo.country: + if hasattr(institution.geo, "country") and institution.geo.country: hint_parts.append(institution.geo.country) elif institution.country_code: hint_parts.append(institution.country_code) @@ -161,12 +156,7 @@ async def autocomplete_institutions( ) return AutocompleteResponse( - meta=AutocompleteResponseMeta( - count=response.meta.count if response.meta else len(results), - db_response_time_ms=( - response.meta.db_response_time_ms if response.meta else None - ), - ), + meta=AutocompleteResponseMeta(count=len(results)), results=results, ) diff --git a/service/src/main/inse/institutions/service.py b/service/src/main/inse/institutions/service.py index 16c7d676..5c08bbdf 100644 --- a/service/src/main/inse/institutions/service.py +++ b/service/src/main/inse/institutions/service.py @@ -23,17 +23,7 @@ router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTI @lru_cache def get_institutions_search_client() -> InstitutionsSearchClient: - settings = get_settings() - if not settings.elasticsearch_url: - raise ValueError("Elasticsearch URL is missing in settings.") - if not settings.elasticsearch_api_key: - raise ValueError("Elasticsearch API key is missing in settings.") - - return InstitutionsSearchClient( - api_key=settings.elasticsearch_api_key, - base_url=settings.elasticsearch_url, - ) - + return InstitutionsSearchClient() @router.get( "/autocomplete", @@ -62,12 +52,14 @@ async def autocomplete_institutions( int, Query(description="Maximum number of autocomplete options.", ge=1, le=25), ] = 10, + client: Annotated[InstitutionsSearchClient, Depends(get_institutions_search_client)] = None, ): return await logic.autocomplete_institutions( query=query, country_code=country_code, institution_type=institution_type, limit=limit, + client=client, ) @@ -155,4 +147,3 @@ async def get_institution( ], ) -> Institution: return await logic.get_institution_by_id(raw_institution_id=id, client=client) - diff --git a/service/src/main/inse/institutions/test_logic.py b/service/src/main/inse/institutions/test_logic.py index e079ff8e..bebf52c0 100644 --- a/service/src/main/inse/institutions/test_logic.py +++ b/service/src/main/inse/institutions/test_logic.py @@ -176,61 +176,3 @@ async def test_list_institutions_accepts_practical_openalex_type_variants(): assert result.results[0].counts_by_year[0].cited_by_count is None assert result.group_by[0].key == "true" - -@pytest.mark.anyio -async def test_autocomplete_institutions_returns_frontend_options(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.url.params["search"] == "Duisburg Essen" - assert request.url.params["filter"] == "country_code:DE,type:education" - assert request.url.params["sort"] == "works_count:desc" - assert request.url.params["per_page"] == "5" - assert request.url.params["select"] == ( - "id,ror,display_name,country_code,type,works_count," - "cited_by_count,geo" - ) - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "db_response_time_ms": 12}, - "results": [ - { - "id": "https://openalex.org/I123", - "ror": "https://ror.org/04mz5ra38", - "display_name": "University of Duisburg-Essen", - "country_code": "DE", - "type": "education", - "works_count": 123, - "cited_by_count": 456, - "geo": { - "city": "Duisburg", - "country": "Germany", - }, - } - ], - }, - ) - - client = OpenAlexInstitutionsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), - ) - - result = await logic.autocomplete_institutions( - query="Duisburg Essen", - country_code="DE", - institution_type="education", - limit=5, - client=client, - ) - - assert result.meta.count == 1 - assert result.meta.db_response_time_ms == 12 - assert len(result.results) == 1 - option = result.results[0] - assert option.id == "https://openalex.org/I123" - assert option.display_name == "University of Duisburg-Essen" - assert option.hint == "Duisburg · Germany · education" - assert option.works_count == 123 - assert option.cited_by_count == 456 - assert option.entity_type == "institution" - assert option.external_id == "https://ror.org/04mz5ra38" diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index a81ae678..6121af94 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -55,13 +55,20 @@ class Institution(BaseModel): updated_date: Optional[datetime] = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).") __properties: ClassVar[List[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"] + @field_validator('created_date', mode='before') + @classmethod + def normalize_created_date(cls, v: Any) -> Any: + if isinstance(v, str) and len(v) > 10: + return v[:10] + return v + @field_validator('type') def type_validate_enum(cls, value): """Validates the enum""" if value is None: return value - if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): + if value not in set(['education','funder', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']): raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')") return value @@ -154,5 +161,3 @@ class Institution(BaseModel): "updated_date": obj.get("updated_date") }) return _obj - -