diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index f360fd31..bf2b23cb 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -36,6 +36,8 @@ class ESIndex(StrEnum): OPENALEX_PUBLICATIONS = "openalex-publications" OPENALEX_COUNTRIES = "openalex-countries" OPENALEX_CONTINENTS = "openalex-continents" + OPENALEX_TOPICS = "openalex-topics" + OPENALEX_TOPIC_VECTORS = "topicvectors" EPO_INDEX = "epo_index_1.0" USPTO_INDEX = "uspto_patents_3.0" diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py index eced478e..cec2bfa6 100644 --- a/service/src/main/inse/topics/logic.py +++ b/service/src/main/inse/topics/logic.py @@ -4,13 +4,12 @@ Business logic for OpenAlex topics. """ -import asyncio import logging from copy import deepcopy from typing import Any - -import httpx +import asyncio from pydantic import ValidationError + from inse.exceptions import ( UpstreamAPIException, BadRequestException, @@ -23,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import ( AutocompleteResponseResultsInner, ) from inse.models.openalex.topics_list_response import TopicsListResponse -from inse.model import ESCluster -from .search_client import OpenAlexTopicsClient +from inse.model import ESCluster, ESIndex +from .search_client import TopicsSearchClient logger = logging.getLogger(__name__) @@ -40,15 +39,15 @@ async def list_topics( cursor: str | None = None, sample: int | None = None, select: str | None = None, - client: OpenAlexTopicsClient | None = None, + client: TopicsSearchClient | None = None, ) -> TopicsListResponse: if sample is not None and (sort or page not in (None, 1)): raise BadRequestException("sample cannot be combined with sort or page.") - openalex_client = client or OpenAlexTopicsClient() + topics_client = client or TopicsSearchClient() try: - data = await openalex_client.list_topics( + data = await topics_client.list_topics( search=search, filter=filter, sort=sort, @@ -59,25 +58,24 @@ async def list_topics( sample=sample, select=select, ) - except httpx.HTTPStatusError as exc: - status_code = exc.response.status_code - detail = "OpenAlex topics request failed." - try: - error_body = exc.response.json() - detail = error_body.get("message") or error_body.get("error") or detail - except ValueError: - if exc.response.text: - detail = exc.response.text - raise UpstreamAPIException(message=detail, status_code=status_code) from exc - except httpx.HTTPError as exc: - logger.exception("OpenAlex topics request failed.") + except ValueError as exc: + raise BadRequestException(str(exc)) from exc + except ElasticsearchException as exc: + logger.exception("OpenAlex topics Elasticsearch request failed.") raise UpstreamAPIException( - message="OpenAlex topics request failed.", + message="OpenAlex topics Elasticsearch request failed.", status_code=502, ) from exc try: - normalized_data = _normalize_topics_response(data) + openalex_style_data = _elasticsearch_to_topics_response( + data, + per_page=per_page, + page=page, + cursor=cursor, + group_by=group_by, + ) + normalized_data = _normalize_topics_response(openalex_style_data) return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse() except ValidationError as exc: logger.exception("OpenAlex topics response could not be parsed.") @@ -94,7 +92,7 @@ async def autocomplete_topics( field_id: str | None = None, subfield_id: str | None = None, limit: int = 10, - client: OpenAlexTopicsClient | None = None, + client: TopicsSearchClient | None = None, ) -> AutocompleteResponse: filters = [] if domain_id: @@ -153,6 +151,99 @@ async def autocomplete_topics( ) +def _elasticsearch_to_topics_response( + data: dict[str, Any], + *, + per_page: int, + page: int | None, + cursor: str | None, + group_by: str | None, +) -> dict[str, Any]: + """ + Converts an Elasticsearch search response into the OpenAlex-style topics + response expected by TopicsListResponse. + + Elasticsearch response shape: + + { + "took": 12, + "hits": { + "total": {"value": 123}, + "hits": [ + {"_source": {...}, "sort": [...]} + ] + }, + "aggregations": {...} + } + + OpenAlex-style response shape: + + { + "meta": {...}, + "results": [...], + "group_by": [...] + } + """ + hits_root = data.get("hits") or {} + raw_hits = hits_root.get("hits") or [] + + total = hits_root.get("total") + if isinstance(total, dict): + count = total.get("value") + else: + count = total + + results: list[dict[str, Any]] = [] + for hit in raw_hits: + if not isinstance(hit, dict): + continue + + source = hit.get("_source") + if isinstance(source, dict): + results.append(source) + + groups = _extract_group_by_results(data) if group_by else [] + + meta = { + "count": count, + "db_response_time_ms": data.get("took"), + "page": page if cursor is None else None, + "per_page": per_page, + "groups_count": len(groups) if group_by else None, + "next_cursor": (data.get("meta") or {}).get("next_cursor"), + "cost_usd": None, + } + + return { + "meta": meta, + "results": results, + "group_by": groups, + } + + +def _extract_group_by_results(data: dict[str, Any]) -> list[dict[str, Any]]: + aggregations = data.get("aggregations") or {} + group_by_agg = aggregations.get("group_by") or {} + buckets = group_by_agg.get("buckets") or [] + + groups: list[dict[str, Any]] = [] + + for bucket in buckets: + if not isinstance(bucket, dict): + continue + + key = bucket.get("key") + groups.append( + { + "key": key, + "key_display_name": bucket.get("key_as_string") or key, + "count": bucket.get("doc_count"), + } + ) + + return groups + + def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]: normalized = deepcopy(data) @@ -264,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None: return f"{text}T00:00:00Z" return text - # Configuration for vector search similarity thresholds and boosts SIMILARITY_THRESHOLD = ( 0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1 @@ -388,7 +478,7 @@ async def vector_search_topics( try: raw_results = await elasticsearch.search( - index="topicvectors", body=body, cluster=ESCluster.NES + index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES ) except Exception as exc: logger.exception("Elasticsearch vector search failed with unexpected error.") @@ -458,7 +548,7 @@ async def vector_search_topics_batch( ) tasks.append( elasticsearch.search( - index="topicvectors", body=body, cluster=ESCluster.NES + index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES ) ) diff --git a/service/src/main/inse/topics/search_client.py b/service/src/main/inse/topics/search_client.py index 7c70afa0..b6ec024a 100644 --- a/service/src/main/inse/topics/search_client.py +++ b/service/src/main/inse/topics/search_client.py @@ -1,33 +1,200 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- """ -HTTP client for OpenAlex topics. +Elasticsearch search client for OpenAlex topics. """ +from __future__ import annotations + +import base64 +import json from typing import Any -import httpx +from inse.model import ESCluster, ESIndex from .. import config +from inse.integrations.elasticsearch import search as elasticsearch_search -class OpenAlexTopicsClient: +class TopicsSearchClient: + """ + Search client for OpenAlex topics backed by Elasticsearch. + + This replaces the old OpenAlex HTTP API client and uses the internal + Elasticsearch wrapper instead. + """ + + DEFAULT_SEARCH_FIELDS = [ + "display_name^5", + "description^3", + "keywords", + "domain.display_name^2", + "field.display_name^2", + "subfield.display_name^2", + ] + def __init__( self, - base_url: str | None = None, - api_key: str | None = None, - timeout: float | None = None, - transport: httpx.AsyncBaseTransport | None = None, + *, + index: ESIndex | str | None = None, + cluster: ESCluster = ESCluster.NES, ): - self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/") - self.api_key = api_key if api_key is not None else config.settings.openalex_api_key - self.timeout = ( - timeout - if timeout is not None - else config.settings.openalex_api_timeout_seconds - ) - self.transport = transport + self.index = index or self._default_index() + self.cluster = cluster - def list_topics_params( + @staticmethod + def _default_index() -> str: + """ + Resolve the OpenAlex topics index name. + + Prefer a configured value if present, otherwise fall back to a sensible + default string index name. + """ + return ( + ESIndex.OPENALEX_TOPICS.value + ) + + @staticmethod + def _split_csv(value: str | None) -> list[str]: + if not value: + return [] + return [part.strip() for part in value.split(",") if part.strip()] + + @staticmethod + def _encode_cursor(sort_values: list[Any]) -> str: + raw = json.dumps(sort_values).encode("utf-8") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + @staticmethod + def _decode_cursor(cursor: str | None) -> list[Any] | None: + if not cursor or cursor == "*": + return None + + padding = "=" * (-len(cursor) % 4) + raw = base64.urlsafe_b64decode(cursor + padding) + return json.loads(raw.decode("utf-8")) + + @staticmethod + def _parse_select(select: str | None) -> list[str] | None: + fields = TopicsSearchClient._split_csv(select) + return fields or None + + @staticmethod + def _parse_sort(sort: str | None) -> list[dict[str, Any]] | None: + """ + Parses OpenAlex-style sort syntax into Elasticsearch sort syntax. + + Examples: + "works_count:desc" + "cited_by_count:desc,display_name:asc" + "-works_count" + """ + parts = TopicsSearchClient._split_csv(sort) + if not parts: + return None + + parsed: list[dict[str, Any]] = [] + + for part in parts: + direction = "asc" + field = part + + if part.startswith("-"): + direction = "desc" + field = part[1:] + elif ":" in part: + field, direction = part.split(":", 1) + field = field.strip() + direction = direction.strip().lower() + + if direction not in {"asc", "desc"}: + direction = "asc" + + if field in {"score", "_score", "relevance_score"}: + parsed.append({"_score": {"order": direction}}) + else: + parsed.append({field: {"order": direction, "missing": "_last"}}) + + return parsed + + @staticmethod + def _parse_filter_clause(expression: str) -> tuple[dict[str, Any] | None, bool]: + """ + Parses a single simple OpenAlex-style filter expression. + + Supported examples: + "works_count:>100" + "works_count:>=100" + "display_name:Physics" + "ids.openalex:T123" + "field.id:F1|F2" + "is_active:true" + "is_active:!true" + + Returns: + tuple[clause, is_negative] + """ + if ":" not in expression: + return None, False + + field, value = expression.split(":", 1) + field = field.strip() + value = value.strip() + + if not field or not value: + return None, False + + is_negative = False + if value.startswith("!"): + is_negative = True + value = value[1:].strip() + + range_ops = { + ">=": "gte", + "<=": "lte", + ">": "gt", + "<": "lt", + } + + for prefix, op in range_ops.items(): + if value.startswith(prefix): + range_value = value[len(prefix):].strip() + return {"range": {field: {op: range_value}}}, is_negative + + if "|" in value: + values = [v.strip() for v in value.split("|") if v.strip()] + return {"terms": {field: values}}, is_negative + + lowered = value.lower() + if lowered == "true": + typed_value: Any = True + elif lowered == "false": + typed_value = False + else: + typed_value = value + + return {"term": {field: typed_value}}, is_negative + + @classmethod + def _parse_filters( + cls, + filter: str | None, + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + filter_clauses: list[dict[str, Any]] = [] + must_not_clauses: list[dict[str, Any]] = [] + + for expression in cls._split_csv(filter): + clause, is_negative = cls._parse_filter_clause(expression) + if clause is None: + continue + + if is_negative: + must_not_clauses.append(clause) + else: + filter_clauses.append(clause) + + return filter_clauses, must_not_clauses + + def build_search_body( self, *, search: str | None = None, @@ -40,28 +207,118 @@ class OpenAlexTopicsClient: sample: int | None = None, select: str | None = None, ) -> dict[str, Any]: - params: dict[str, Any] = {"per_page": per_page} + """ + Build the Elasticsearch search body from the previous OpenAlex-style API + parameters. + """ + filter_clauses, must_not_clauses = self._parse_filters(filter) + + must_clauses: list[dict[str, Any]] = [] if search: - params["search"] = search - if filter: - params["filter"] = filter - if sort: - params["sort"] = sort - if group_by: - params["group_by"] = group_by - if cursor: - params["cursor"] = cursor - elif page is not None: - params["page"] = page - if sample is not None: - params["sample"] = sample - if select: - params["select"] = select - if self.api_key: - params["api_key"] = self.api_key + must_clauses.append( + { + "multi_match": { + "query": search, + "fields": self.DEFAULT_SEARCH_FIELDS, + "type": "best_fields", + "operator": "and", + } + } + ) - return params + if must_clauses or filter_clauses or must_not_clauses: + query: dict[str, Any] = { + "bool": { + "must": must_clauses or [{"match_all": {}}], + "filter": filter_clauses, + "must_not": must_not_clauses, + } + } + else: + query = {"match_all": {}} + + if sample is not None: + query = { + "function_score": { + "query": query, + "random_score": {}, + } + } + + size = sample if sample is not None else per_page + + body: dict[str, Any] = { + "query": query, + "size": size, + "track_total_hits": True, + } + + source = self._parse_select(select) + if source is not None: + body["_source"] = source + + sort_clause = self._parse_sort(sort) + if sort_clause is not None: + body["sort"] = sort_clause + + search_after = self._decode_cursor(cursor) + if search_after is not None: + body["search_after"] = search_after + elif cursor is None and page is not None: + body["from"] = max(page - 1, 0) * per_page + + if group_by: + body["size"] = 0 + body["aggs"] = { + "group_by": { + "terms": { + "field": group_by, + "size": per_page, + } + } + } + + return body + + async def search_topics( + self, + *, + search: str | None = None, + filter: str | None = None, + sort: str | None = None, + group_by: str | None = None, + per_page: int = 25, + page: int | None = 1, + cursor: str | None = None, + sample: int | None = None, + select: str | None = None, + ) -> dict[str, Any]: + body = self.build_search_body( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) + + result = await elasticsearch_search( + index=self.index, + body=body, + cluster=self.cluster, + ) + + hits = result.get("hits", {}).get("hits", []) + if hits: + last_sort = hits[-1].get("sort") + if last_sort is not None: + result.setdefault("meta", {})["next_cursor"] = self._encode_cursor(last_sort) + + return result async def list_topics( self, @@ -76,24 +333,17 @@ class OpenAlexTopicsClient: sample: int | None = None, select: str | None = None, ) -> dict[str, Any]: - async with httpx.AsyncClient( - base_url=self.base_url, - timeout=self.timeout, - transport=self.transport, - ) as client: - response = await client.get( - "/topics", - params=self.list_topics_params( - search=search, - filter=filter, - sort=sort, - group_by=group_by, - per_page=per_page, - page=page, - cursor=cursor, - sample=sample, - select=select, - ), - ) - response.raise_for_status() - return response.json() + """ + Backwards-compatible alias for the old OpenAlex client method name. + """ + return await self.search_topics( + search=search, + filter=filter, + sort=sort, + group_by=group_by, + per_page=per_page, + page=page, + cursor=cursor, + sample=sample, + select=select, + ) \ No newline at end of file diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py index 5e88a461..60b8b1f1 100644 --- a/service/src/main/inse/topics/test_logic.py +++ b/service/src/main/inse/topics/test_logic.py @@ -1,9 +1,7 @@ -import httpx import pytest -from inse.exceptions import BadRequestException +from inse.exceptions import BadRequestException from inse.topics import logic -from inse.topics.search_client import OpenAlexTopicsClient @pytest.fixture @@ -11,108 +9,144 @@ def anyio_backend(): return "asyncio" +class FakeTopicsSearchClient: + def __init__(self, response: dict): + self.response = response + self.calls: list[dict] = [] + + async def list_topics(self, **kwargs): + self.calls.append(kwargs) + return self.response + + @pytest.mark.anyio -async def test_list_topics_maps_openalex_response_to_model(): - def handler(_: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ +async def test_list_topics_maps_elasticsearch_response_to_model(): + client = FakeTopicsSearchClient( + { + "took": 12, + "hits": { + "total": {"value": 1, "relation": "eq"}, + "hits": [ { - "id": "https://openalex.org/T12419", - "display_name": "Machine learning", - "description": "Methods that learn from data.", - "keywords": ["machine learning", "classification"], - "subfield": { - "id": "https://openalex.org/subfields/1702", - "display_name": "Artificial Intelligence", + "_id": "https://openalex.org/T12419", + "_source": { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "keywords": ["machine learning", "classification"], + "subfield": { + "id": "https://openalex.org/subfields/1702", + "display_name": "Artificial Intelligence", + }, + "field": { + "id": "https://openalex.org/fields/17", + "display_name": "Computer Science", + }, + "domain": { + "id": "https://openalex.org/domains/4", + "display_name": "Physical Sciences", + }, + "works_count": 123, + "cited_by_count": 456, + "ids": { + "openalex": "https://openalex.org/T12419", + "wikipedia": "https://en.wikipedia.org/wiki/Machine_learning", + }, + "works_api_url": ( + "https://api.openalex.org/works?" + "filter=topics.id:T12419" + ), + "created_date": "2023-12-25", + "updated_date": "2023-11-07T05:31:56Z", }, - "field": { - "id": "https://openalex.org/fields/17", - "display_name": "Computer Science", - }, - "domain": { - "id": "https://openalex.org/domains/4", - "display_name": "Physical Sciences", - }, - "works_count": 123, - "cited_by_count": 456, - "ids": { - "openalex": "https://openalex.org/T12419", - "wikipedia": "https://en.wikipedia.org/wiki/Machine_learning", - }, - "works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419", - "created_date": "2023-12-25", - "updated_date": "2023-11-07T05:31:56Z", - } - ], - "group_by": [ - { - "key": "https://openalex.org/domains/4", - "key_display_name": "Physical Sciences", - "count": 1, } ], }, - ) - - client = OpenAlexTopicsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), + "aggregations": { + "group_by": { + "buckets": [ + { + "key": "https://openalex.org/domains/4", + "key_as_string": "Physical Sciences", + "doc_count": 1, + } + ] + } + }, + } ) - result = await logic.list_topics(search="machine learning", client=client) + result = await logic.list_topics( + search="machine learning", + group_by="domain.id", + client=client, + ) + + assert client.calls[0]["search"] == "machine learning" + assert client.calls[0]["group_by"] == "domain.id" assert result.meta.count == 1 + assert result.meta.db_response_time_ms == 12 + topic = result.results[0] assert topic.display_name == "Machine learning" assert topic.var_field.display_name == "Computer Science" assert topic.subfield.display_name == "Artificial Intelligence" assert topic.domain.display_name == "Physical Sciences" assert topic.ids.openalex == "https://openalex.org/T12419" + + assert result.group_by[0].key == "https://openalex.org/domains/4" assert result.group_by[0].key_display_name == "Physical Sciences" + assert result.group_by[0].count == 1 @pytest.mark.anyio async def test_list_topics_rejects_sample_with_sort(): - with pytest.raises(BadRequestException) as exc_info: + with pytest.raises(BadRequestException): await logic.list_topics(sample=10, sort="works_count:desc") @pytest.mark.anyio async def test_list_topics_accepts_practical_openalex_type_variants(): - def handler(_: httpx.Request) -> httpx.Response: - return httpx.Response( - 200, - json={ - "meta": {"count": "1", "page": "1", "per_page": "25"}, - "results": [ + client = FakeTopicsSearchClient( + { + "took": "10", + "hits": { + "total": {"value": "1", "relation": "eq"}, + "hits": [ { - "id": 123, - "display_name": 456, - "description": True, - "keywords": ["topic", 123], - "subfield": {"id": 1, "display_name": 2}, - "field": {"id": 3, "display_name": 4}, - "domain": {"id": 5, "display_name": 6}, - "works_count": "12.0", - "cited_by_count": False, - "ids": {"openalex": 123, "wikipedia": 456}, - "created_date": "2023-12-25T10:11:12Z", - "updated_date": "2023-12-25", + "_id": "123", + "_source": { + "id": 123, + "display_name": 456, + "description": True, + "keywords": ["topic", 123], + "subfield": {"id": 1, "display_name": 2}, + "field": {"id": 3, "display_name": 4}, + "domain": {"id": 5, "display_name": 6}, + "works_count": "12.0", + "cited_by_count": False, + "ids": {"openalex": 123, "wikipedia": 456}, + "created_date": "2023-12-25T10:11:12Z", + "updated_date": "2023-12-25", + }, } ], - "group_by": [{"key": True, "count": "1"}], }, - ) - - client = OpenAlexTopicsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), + "aggregations": { + "group_by": { + "buckets": [ + { + "key": True, + "doc_count": "1", + } + ] + } + }, + } ) - result = await logic.list_topics(client=client) + result = await logic.list_topics(group_by="domain.id", client=client) topic = result.results[0] assert topic.id == "123" @@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants(): @pytest.mark.anyio async def test_autocomplete_topics_returns_frontend_options(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.url.params["search"] == "machine learning" - assert request.url.params["filter"] == ( - "domain.id:https://openalex.org/domains/4," - "field.id:https://openalex.org/fields/17," - "subfield.id:https://openalex.org/subfields/1702" - ) - assert request.url.params["sort"] == "works_count:desc" - assert request.url.params["per_page"] == "5" - assert request.url.params["select"] == ( - "id,display_name,description,keywords,subfield,field,domain," - "works_count,cited_by_count,ids" - ) - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "db_response_time_ms": 12}, - "results": [ + client = FakeTopicsSearchClient( + { + "took": 12, + "hits": { + "total": {"value": 1, "relation": "eq"}, + "hits": [ { - "id": "https://openalex.org/T12419", - "display_name": "Machine learning", - "description": "Methods that learn from data.", - "field": {"display_name": "Computer Science"}, - "subfield": {"display_name": "Artificial Intelligence"}, - "domain": {"display_name": "Physical Sciences"}, - "works_count": 123, - "cited_by_count": 456, - "ids": {"openalex": "https://openalex.org/T12419"}, + "_id": "https://openalex.org/T12419", + "_source": { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + "description": "Methods that learn from data.", + "field": {"display_name": "Computer Science"}, + "subfield": { + "display_name": "Artificial Intelligence", + }, + "domain": {"display_name": "Physical Sciences"}, + "works_count": 123, + "cited_by_count": 456, + "ids": { + "openalex": "https://openalex.org/T12419", + }, + }, } ], }, - ) - - client = OpenAlexTopicsClient( - api_key="test-key", - transport=httpx.MockTransport(handler), + } ) result = await logic.autocomplete_topics( @@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options(): client=client, ) + assert client.calls[0]["search"] == "machine learning" + assert client.calls[0]["filter"] == ( + "domain.id:https://openalex.org/domains/4," + "field.id:https://openalex.org/fields/17," + "subfield.id:https://openalex.org/subfields/1702" + ) + assert client.calls[0]["sort"] == "works_count:desc" + assert client.calls[0]["per_page"] == 5 + assert client.calls[0]["page"] == 1 + assert client.calls[0]["select"] == ( + "id,display_name,description,keywords,subfield,field,domain," + "works_count,cited_by_count,ids" + ) + 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/T12419" assert option.display_name == "Machine learning" @@ -190,4 +230,4 @@ async def test_autocomplete_topics_returns_frontend_options(): assert option.works_count == 123 assert option.cited_by_count == 456 assert option.entity_type == "topic" - assert option.external_id == "https://openalex.org/T12419" + assert option.external_id == "https://openalex.org/T12419" \ No newline at end of file diff --git a/service/src/main/inse/topics/test_search_client.py b/service/src/main/inse/topics/test_search_client.py index 69c16a82..74de07f7 100644 --- a/service/src/main/inse/topics/test_search_client.py +++ b/service/src/main/inse/topics/test_search_client.py @@ -1,7 +1,7 @@ -import httpx import pytest -from inse.topics.search_client import OpenAlexTopicsClient +from inse.model import ESCluster, ESIndex +from inse.topics.search_client import TopicsSearchClient @pytest.fixture @@ -9,10 +9,10 @@ def anyio_backend(): return "asyncio" -def test_list_topics_params_include_openalex_query_parameters(): - client = OpenAlexTopicsClient(api_key="test-key") +def test_build_search_body_includes_openalex_query_parameters(): + client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES) - params = client.list_topics_params( + body = client.build_search_body( search="machine learning", filter="domain.id:4,works_count:>1000", sort="works_count:desc", @@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters(): select="id,display_name", ) - assert params == { - "search": "machine learning", - "filter": "domain.id:4,works_count:>1000", - "sort": "works_count:desc", - "group_by": "domain.id", - "per_page": 10, - "page": 2, - "select": "id,display_name", - "api_key": "test-key", + assert body["query"] == { + "bool": { + "must": [ + { + "multi_match": { + "query": "machine learning", + "fields": client.DEFAULT_SEARCH_FIELDS, + "type": "best_fields", + "operator": "and", + } + } + ], + "filter": [ + {"term": {"domain.id": "4"}}, + {"range": {"works_count": {"gt": "1000"}}}, + ], + "must_not": [], + } + } + + assert body["_source"] == ["id", "display_name"] + assert body["sort"] == [ + {"works_count": {"order": "desc", "missing": "_last"}} + ] + + # group_by queries use aggregations and no regular hits + assert body["size"] == 0 + assert body["from"] == 10 + assert body["track_total_hits"] is True + assert body["aggs"] == { + "group_by": { + "terms": { + "field": "domain.id", + "size": 10, + } + } } -def test_list_topics_params_prefers_cursor_over_page(): - client = OpenAlexTopicsClient(api_key="test-key") +def test_build_search_body_prefers_cursor_over_page(): + client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES) - params = client.list_topics_params(cursor="*", page=3) + cursor = client._encode_cursor(["Machine learning", "https://openalex.org/T12419"]) - assert params["cursor"] == "*" - assert "page" not in params + body = client.build_search_body( + cursor=cursor, + page=3, + per_page=25, + ) + + assert body["search_after"] == [ + "Machine learning", + "https://openalex.org/T12419", + ] + assert "from" not in body + + +def test_build_search_body_with_plain_cursor_star_does_not_use_page_offset(): + client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES) + + body = client.build_search_body( + cursor="*", + page=3, + per_page=25, + ) + + assert "search_after" not in body + assert "from" not in body @pytest.mark.anyio -async def test_list_topics_calls_openalex_topics_endpoint(): - def handler(request: httpx.Request) -> httpx.Response: - assert request.method == "GET" - assert request.url.path == "/topics" - assert request.url.params["search"] == "machine learning" - assert request.url.params["api_key"] == "test-key" - return httpx.Response( - 200, - json={ - "meta": {"count": 1, "page": 1, "per_page": 25}, - "results": [ +async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch): + captured = {} + + async def fake_elasticsearch_search(*, index, body, cluster): + captured["index"] = index + captured["body"] = body + captured["cluster"] = cluster + + return { + "took": 3, + "hits": { + "total": {"value": 1, "relation": "eq"}, + "hits": [ { - "id": "https://openalex.org/T12419", - "display_name": "Machine learning", + "_id": "https://openalex.org/T12419", + "_source": { + "id": "https://openalex.org/T12419", + "display_name": "Machine learning", + }, + "sort": [1000, "https://openalex.org/T12419"], } ], }, - ) + } - client = OpenAlexTopicsClient( - base_url="https://api.openalex.org", - api_key="test-key", - transport=httpx.MockTransport(handler), + monkeypatch.setattr( + "inse.topics.search_client.elasticsearch_search", + fake_elasticsearch_search, ) + client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES) + result = await client.list_topics(search="machine learning") - assert result["meta"]["count"] == 1 - assert result["results"][0]["display_name"] == "Machine learning" + assert captured["index"] == ESIndex.OPENALEX_TOPICS + assert captured["cluster"] == ESCluster.NES + + assert captured["body"]["query"]["bool"]["must"] == [ + { + "multi_match": { + "query": "machine learning", + "fields": client.DEFAULT_SEARCH_FIELDS, + "type": "best_fields", + "operator": "and", + } + } + ] + assert captured["body"]["size"] == 25 + assert captured["body"]["from"] == 0 + assert captured["body"]["track_total_hits"] is True + + assert result["hits"]["total"]["value"] == 1 + assert result["hits"]["hits"][0]["_source"]["display_name"] == "Machine learning" + assert result["meta"]["next_cursor"] is not None \ No newline at end of file diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.html b/webapp/src/app/modules/keywords-search/keywords-search.component.html index 26a29eea..a46bb8b3 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.html @@ -83,7 +83,8 @@ mat-stroked-button color="primary" (click)="deselectAll()" - [disabled]="isExtracting()"> + [disabled]="isExtracting()" + matTooltip="Alle extrahierten Keywords abwählen"> select_all Alle abwählen @@ -344,14 +345,16 @@ Quellentext: {{ sourceUrl() }} -
{{ sourceContent() }}
+
} @if (isExtracting() && !keywordsExist()) { } diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.scss b/webapp/src/app/modules/keywords-search/keywords-search.component.scss index 014638f3..4c1e9f85 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.scss @@ -50,6 +50,10 @@ $touch-target: 44px; ::ng-deep app-topic-legend .topic-legend { width: 100%; + + border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8)); + border-bottom: none; + border-radius: 4px; margin: 0; } } @@ -66,7 +70,8 @@ $touch-target: 44px; .toolbar-wrapper { display: grid; grid-template-columns: 3fr 1.3fr; - border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8)); + border-bottom: none; } .toolbar-controls--placeholder { @@ -188,14 +193,13 @@ mat-button-toggle-group { } .keyword-card { - background-color: var(--sg-background); - padding: 0.5rem; - + padding: 0 !important; + background: var(--sg-background-muted, #f4f5f7); .mat-card-header { padding: 0 0 0.5rem 0; } - .mat-card-content { + .mat-mdc-card-content { padding: 0; } } @@ -209,12 +213,12 @@ mat-button-toggle-group { } .table-head { - border-top: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); + border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8)); padding-top: 0.5rem; display: grid; grid-template-columns: repeat(3, 1fr) 1.3fr; column-gap: 1rem; - border-bottom: 2px solid var(--sg-divider, rgba(0, 0, 0, 0.12)); + border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8)); padding-bottom: 0.5rem; background: var(--sg-background-muted, #f4f5f7); } @@ -235,12 +239,13 @@ mat-button-toggle-group { } .table-body { + min-height: 200px; display: grid; grid-template-columns: repeat(3, 1fr) 1.3fr; column-gap: 1rem; row-gap: 0.4rem; align-items: start; - border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + //border-left: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8)); } .table-col { @@ -249,7 +254,7 @@ mat-button-toggle-group { min-width: 0; padding: 0.5rem; height: 100%; - border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.08)); + border-right: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.8)); &:last-child { border-right: none; @@ -266,7 +271,7 @@ mat-button-toggle-group { } .thick-border { - border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.1)) !important; + border-right: 5px solid var(--sg-divider, rgba(0, 0, 0, 0.08)) !important; } @container keyword-tool (max-width: #{$tablet}) { @@ -504,7 +509,7 @@ mat-button-toggle-group { margin: 0.75rem 0; background: var(--sg-background-muted, #f5f5f5); border-radius: 4px; - border-left: 4px solid var(--sg-primary, #1976d2); + //border-left: 4px solid var(--sg-primary, #1976d2); .mat-expansion-panel-header { padding: 0.5rem 0.75rem; @@ -554,7 +559,6 @@ mat-button-toggle-group { PROGRESS BAR ============================================================ */ .progress-container { - min-height: 300px; margin-top: 0.5rem; position: relative; padding: 1rem; diff --git a/webapp/src/app/modules/keywords-search/keywords-search.component.ts b/webapp/src/app/modules/keywords-search/keywords-search.component.ts index 4cd4f59e..f63bec41 100644 --- a/webapp/src/app/modules/keywords-search/keywords-search.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-search.component.ts @@ -45,6 +45,7 @@ import { } from '../../resolvers/utils/topic-legend'; import { MatTooltipModule } from '@angular/material/tooltip'; import { A11yModule } from '@angular/cdk/a11y'; +import { DomSanitizer } from '@angular/platform-browser'; type InputMode = 'url' | 'text'; type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual'; type KeywordView = 'llm' | 'topic'; @@ -77,6 +78,7 @@ type KeywordView = 'llm' | 'topic'; }) export class KeywordsSearchComponent { private readonly formBuilder = inject(FormBuilder); + private readonly sanitizer = inject(DomSanitizer); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly destroyRef = inject(DestroyRef); @@ -128,6 +130,55 @@ export class KeywordsSearchComponent { readonly sourceContent = signal(''); readonly sourceUrl = signal(null); + readonly highlightedSourceContent = computed(() => { + const content = this.sourceContent(); + if (!content) return ''; + + const selectedKeywords = this.selectedKeywords(); + if (selectedKeywords.length === 0) return content; + + let highlightedContent = content; + + // replace the keyword with highlighted spans + for (const keyword of selectedKeywords) { + const normalizedKeyword = this.normalizeKeyword(keyword); + + // Find the first keyword entry that matches this normalized keyword + const entry = this.allKeywordEntries().find( + (e) => + this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword, + ); + + if (entry) { + const topic = this.getTopic(entry); + if (topic) { + const color = this.getTopicColor(topic); + // Escape HTML special characters in the keyword before using it in HTML + const escapedKeyword = keyword + .replace(/&/g, '&') + .replace(//g, '>'); + + // Create the replacement span HTML + const replacement = `${escapedKeyword}`; + + const escapedRegexKeyword = keyword.replace( + /[.*+?^${}()|[\]\\]/g, + '\\$&', + ); + const regex = new RegExp(escapedRegexKeyword, 'g'); + + highlightedContent = highlightedContent.replace(regex, replacement); + } + } + } + console.log( + 'Highlighted content:', + this.sanitizer.bypassSecurityTrustHtml(highlightedContent), + ); + return this.sanitizer.bypassSecurityTrustHtml(highlightedContent); + }); + private isRestoringState = false; // Set right before we call router.navigate() ourselves (from diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html index 91a2bdcc..bf164795 100644 --- a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.html @@ -45,9 +45,19 @@ } @for (topic of topics(); track topic) { - {{ - topic.display_name - }} + +
+
+ {{ topic.display_name }} +
+ +
+ {{ topic.domain?.display_name }} > + {{ topic.field?.display_name }} > + {{ topic.subfield?.display_name }} +
+
} @if ( diff --git a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss index 13b1fac6..3e2ba937 100644 --- a/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss +++ b/webapp/src/app/shared/ui/topic-autocomplete/topic-autocomplete.component.scss @@ -13,3 +13,21 @@ mat-form-field { .topic-field { width: 100%; } +.topic-option { + display: flex; + flex-direction: column; + line-height: 1.2; +} + +.topic-main { + font-size: 14px; + font-weight: 500; +} + +.topic-path { + font-size: 11px; + color: rgba(0, 0, 0, 0.6); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +}