From 59a1f765d0735b218b01ae639d4dc2ea784c34b4 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Wed, 22 Jul 2026 23:14:05 +0200 Subject: [PATCH 01/15] Add DFG projects --- service/src/main/inse/dashboard/service.py | 306 ++++++++++++++---- .../src/main/inse/dashboard/test_service.py | 267 ++++++++++++--- .../dashboard/dashboard.component.html | 14 +- .../dashboard/dashboard.component.scss | 6 +- .../modules/dashboard/dashboard.component.ts | 37 ++- 5 files changed, 505 insertions(+), 125 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ce9a9b2b..a491c51f 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -12,6 +12,8 @@ from inse.integrations import elasticsearch from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.model import ESCluster, ESIndex from inse.patents.org.elastic_search_client import OrgPatentsSearchClient +from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector +from inse.projects.logic import get_person_ids_by_institution_ids from .model import ( DashboardStatisticValue, @@ -264,21 +266,39 @@ async def get_top_authors( works_period: WorksPeriod = "all_time", ) -> TopAuthorStatistics: normalized_id = _normalize_institution_id(institution_id) - authors = await _safe_institution_authors(normalized_id) + + authors, aliases = await asyncio.gather( + _safe_institution_authors(normalized_id), + _safe_institution_aliases(normalized_id, organization_name), + ) + + logger.info( + "Dashboard institution aliases for %s: %s", + organization_name, + aliases, + ) + works = _top_work_authors(authors, works_period) - aliases = await _safe_institution_aliases(normalized_id, organization_name) + projects = await _safe_top_authors( "projects", - _top_project_authors(authors, aliases), + _top_project_authors( + authors=authors, + organization_name=organization_name, + aliases=aliases, + ), ) + patents = await _safe_top_authors( "patents", _top_patent_authors(normalized_id), ) + news = await _safe_top_authors( "news", _top_news_authors(authors), ) + return TopAuthorStatistics( institution_id=normalized_id, works=works, @@ -593,89 +613,251 @@ async def _institution_authors(institution_id: str) -> list[dict[str, Any]]: async def _top_project_authors( authors: list[dict[str, Any]], + organization_name: str, aliases: list[str], ) -> list[TopAuthor]: - if not aliases: + institution_ids = await _dfg_institution_ids_for_organization( + organization_name=organization_name, + ) + + logger.info( + "DFG institution IDs for %s: %s", + organization_name, + institution_ids, + ) + + if not institution_ids: + logger.warning( + "No DFG institution IDs found for organization %s.", + organization_name, + ) return [] - counts: dict[str, int] = {} - names: dict[str, str] = {} - for bucket in await _top_dfg_project_author_buckets(aliases): - key = str(bucket.get("key", "")).strip() - if key: - normalized_key = key.casefold() - names[normalized_key] = key - counts[normalized_key] = counts.get(normalized_key, 0) + int( - bucket.get("doc_count", 0) - ) + + selected_person_ids = set( + await get_person_ids_by_institution_ids( + institution_ids=institution_ids + ) + ) + + logger.info( + "Found %s DFG persons for organization %s.", + len(selected_person_ids), + organization_name, + ) + + if not selected_person_ids: + return [] + + project_ids_by_person: dict[int, set[str]] = {} + names: dict[int, str] = {} + + page = 0 + size = 10000 + processed = 0 + + while True: + project_hits, total = await _dfg_project_author_hits( + page=page, + size=size, + person_ids=selected_person_ids, + aliases=aliases, + ) + + if not project_hits: + break + + for project in project_hits: + project_id = _dfg_project_id(project) + + if not project_id: + continue + + persons = project.get("persons", []) + + if not isinstance(persons, list): + continue + + for person in persons: + if not isinstance(person, dict): + continue + + person_id = person.get("person_id") + full_name = person.get("full_name") + + if person_id is None or not full_name: + continue + + try: + normalized_person_id = int(person_id) + except (TypeError, ValueError): + continue + + + if normalized_person_id not in selected_person_ids: + continue + + project_ids_by_person.setdefault( + normalized_person_id, + set(), + ).add(project_id) + + names[normalized_person_id] = str(full_name).strip() + + processed += len(project_hits) + + if processed >= total: + break + + page += 1 + + institution_authors = { + author["name"].strip().casefold(): author + for author in authors + if author.get("name") + } - institution_authors = {author["name"].casefold(): author for author in authors} ranked = sorted( ( - (name, count) - for name, count in counts.items() - if count > 0 + (person_id, project_ids) + for person_id, project_ids in project_ids_by_person.items() + if project_ids and names.get(person_id) + ), + key=lambda item: ( + -len(item[1]), + names[item[0]].casefold(), ), - key=lambda item: (-item[1], names[item[0]].casefold()), ) - return [ - TopAuthor( - id=( - _short_author_id(institution_authors[name]["id"]) - if name in institution_authors - else None - ), - name=( - institution_authors[name]["name"] - if name in institution_authors - else names[name] - ), - count=count, + + result: list[TopAuthor] = [] + + for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]: + dfg_name = names[person_id] + matched_author = institution_authors.get( + dfg_name.casefold() ) - for name, count in ranked[:TOP_AUTHOR_LIMIT] - ] + + result.append( + TopAuthor( + id=( + _short_author_id(matched_author["id"]) + if matched_author + else None + ), + name=( + matched_author["name"] + if matched_author + else dfg_name + ), + count=len(project_ids), + ) + ) + + logger.info( + "DFG top authors for %s: %s", + organization_name, + [ + { + "name": author.name, + "count": author.count, + "id": author.id, + } + for author in result + ], + ) + + return result -async def _top_dfg_project_author_buckets( +async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]: + page = await autocomplete_institutions_for_selector( + query=organization_name, + page=0, + size=10000, + ) + return [institution.id for institution in page.elements if institution.id is not None] + + +async def _dfg_project_author_hits( + page: int, + size: int, + person_ids: set[int], aliases: list[str], -) -> list[dict[str, Any]]: +) -> tuple[list[dict[str, Any]], int]: response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, body={ - "size": 0, - "query": _dfg_institution_query(aliases), - "aggs": { - "people": { - "terms": { - "script": { - "lang": "painless", - "source": _dfg_involved_persons_script(), + "size": size, + "from": page * size, + "_source": [ + "id", + "project_id", + "persons", + *DFG_INSTITUTION_FIELDS, + ], + "query": { + "bool": { + "must": [ + + _dfg_institution_query(aliases), + + { + "nested": { + "path": "persons", + "query": { + "terms": { + "persons.person_id": sorted( + person_ids + ) + } + }, + } }, - "size": 10000, - } + ] } }, + "sort": [ + { + "id": { + "order": "asc", + "missing": "_last", + } + } + ], }, cluster=ESCluster.INSE, - ) - return ( - response.get("aggregations", {}).get("people", {}).get("buckets", []) + track_total_hits=True, ) + hits_block = response.get("hits", {}) -def _dfg_involved_persons_script() -> str: - return ( - "def names = new HashSet(); " - "def value = params['_source'].containsKey('Beteiligte Personen') " - " ? params['_source']['Beteiligte Personen'] : null; " - "if (value instanceof String && value.length() > 0) { " - " for (name in value.splitOnToken(';')) { " - " def trimmed = name.trim(); " - " if (trimmed.length() > 0) { names.add(trimmed); } " - " } " - "} " - "return new ArrayList(names);" + total_value = hits_block.get("total", 0) + + if isinstance(total_value, dict): + total = int(total_value.get("value", 0)) + else: + total = int(total_value or 0) + + hits = [ + hit.get("_source", {}) + for hit in hits_block.get("hits", []) + if isinstance(hit.get("_source"), dict) + ] + + logger.info( + "Loaded %s of %s matching DFG projects on page %s.", + len(hits), + total, + page, ) + return hits, total + +def _dfg_project_id(project: dict[str, Any]) -> str | None: + project_id = project.get("project_id") + if project_id is None: + project_id = project.get("id") + return str(project_id) if project_id is not None else None + async def _top_patent_authors(institution_id: str) -> list[TopAuthor]: client = OrgPatentsSearchClient() @@ -729,4 +911,4 @@ async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]: ) for bucket in buckets if str(bucket.get("key", "")).casefold() in institution_authors - ][:TOP_AUTHOR_LIMIT] + ][:TOP_AUTHOR_LIMIT] \ No newline at end of file diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 0d2914c0..8244e305 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -1,5 +1,6 @@ from unittest.mock import AsyncMock, patch from datetime import datetime +from types import SimpleNamespace import pytest from fastapi import HTTPException @@ -133,10 +134,42 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): } if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [{"key": "Grace Example", "doc_count": 3}] - } + "hits": { + "total": {"value": 3}, + "hits": [ + { + "_source": { + "id": "ES1", + "project_id": "P1", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + { + "person_id": 99, + "full_name": "Outside Collaborator", + }, + ], + } + }, + { + "_source": { + "id": "ES2", + "project_id": "P2", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + {"person_id": 2, "full_name": "Grace Example"}, + ], + } + }, + { + "_source": { + "id": "ES3", + "project_id": "P2", + "persons": [ + {"person_id": 2, "full_name": "Grace Example"}, + ], + } + }, + ], } } return {"aggregations": {"people": {"buckets": []}}} @@ -145,8 +178,18 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ) as mocked_search, patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ) as mocked_institutions, patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[2]), + ), patch( "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), + new=AsyncMock(return_value=[]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock( @@ -165,7 +208,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): assert result.projects[0].model_dump() == { "id": "A2", "name": "Grace Example", - "count": 3, + "count": 2, } assert result.patents[0].model_dump() == { "id": "A1", @@ -177,20 +220,28 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): "name": "Ada Example", "count": 6, } - project_calls = [ + mocked_institutions.assert_awaited_once_with( + query="Example Org", + page=0, + size=10000, + ) + dfg_project_calls = [ call for call in mocked_search.await_args_list - if call.kwargs["index"] - in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1} + if call.kwargs["index"] == ESIndex.DFG_PROJECTS ] - assert len(project_calls) == 1 - assert project_calls[0].kwargs["index"] == ESIndex.DFG_PROJECTS - assert project_calls[0].kwargs["body"]["query"]["bool"][ - "minimum_should_match" - ] == 1 - assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][ - "people" - ]["terms"]["script"]["source"] + assert len(dfg_project_calls) == 1 + assert dfg_project_calls[0].kwargs["body"]["_source"] == [ + "id", + "project_id", + "persons", + ] + assert dfg_project_calls[0].kwargs["body"]["query"] == { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": [2]}}, + } + } @pytest.mark.anyio @@ -200,10 +251,20 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): return {"hits": {"hits": []}} if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [{"key": "Project Person", "doc_count": 9}] - } + "hits": { + "total": {"value": 9}, + "hits": [ + { + "_source": { + "id": f"P{project_id}", + "project_id": None, + "persons": [ + {"person_id": 9, "full_name": "Project Person"}, + ], + } + } + for project_id in range(9) + ], } } return {"aggregations": {"people": {"buckets": []}}} @@ -212,8 +273,15 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[9]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -227,6 +295,84 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): } +@pytest.mark.anyio +async def test_top_authors_processes_all_dfg_project_pages(): + async def search(**kwargs): + if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: + return {"hits": {"hits": []}} + if kwargs["index"] == ESIndex.DFG_PROJECTS: + if kwargs["body"]["from"] == 0: + return { + "hits": { + "total": {"value": 10001}, + "hits": [ + { + "_source": { + "id": f"ES{project_id}", + "project_id": f"P{project_id}", + "persons": [ + { + "person_id": 9, + "full_name": "Project Person", + }, + ], + } + } + for project_id in range(10000) + ], + } + } + return { + "hits": { + "total": {"value": 10001}, + "hits": [ + { + "_source": { + "id": "ES10000", + "project_id": "P10000", + "persons": [ + {"person_id": 9, "full_name": "Project Person"}, + ], + } + } + ], + } + } + return {"aggregations": {"people": {"buckets": []}}} + + with patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(side_effect=search), + ) as mocked_search, patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace(elements=[SimpleNamespace(id=101)]) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[9]), + ), patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ): + result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") + + assert result.projects[0].model_dump() == { + "id": None, + "name": "Project Person", + "count": 10001, + } + dfg_project_calls = [ + call + for call in mocked_search.await_args_list + if call.kwargs["index"] == ESIndex.DFG_PROJECTS + ] + assert [call.kwargs["body"]["from"] for call in dfg_project_calls] == [ + 0, + 10000, + ] + + @pytest.mark.anyio async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count(): async def search(**kwargs): @@ -234,13 +380,24 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() return {"hits": {"hits": []}} if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [ - {"key": f"Project Person {count}", "doc_count": count} - for count in range(1, 12) - ] - } + "hits": { + "total": {"value": 11}, + "hits": [ + { + "_source": { + "id": f"P{project_id}", + "project_id": None, + "persons": [ + { + "person_id": count, + "full_name": f"Project Person {count}", + } + for count in range(project_id, 12) + ], + } + } + for project_id in range(1, 12) + ], } } return {"aggregations": {"people": {"buckets": []}}} @@ -249,8 +406,15 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=list(range(1, 12))), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -263,7 +427,7 @@ async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count() @pytest.mark.anyio -async def test_top_authors_combines_dfg_involved_people_case_insensitively(): +async def test_top_authors_matches_dfg_project_people_to_openalex_case_insensitively(): async def search(**kwargs): if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: return { @@ -282,14 +446,20 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): } if kwargs["index"] == ESIndex.DFG_PROJECTS: return { - "aggregations": { - "people": { - "buckets": [ - {"key": "Ada Example", "doc_count": 2}, - {"key": "ada example", "doc_count": 3}, - {"key": "DFG Person", "doc_count": 4}, - ] - } + "hits": { + "total": {"value": 1}, + "hits": [ + { + "_source": { + "id": "P1", + "project_id": None, + "persons": [ + {"person_id": 1, "full_name": "ada example"}, + {"person_id": 2, "full_name": "DFG Person"}, + ], + } + } + ], } } return {"aggregations": {"authors": {"buckets": []}}} @@ -298,8 +468,15 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): "inse.dashboard.service.elasticsearch.search", new=AsyncMock(side_effect=search), ), patch( - "inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id", - new=AsyncMock(return_value=["Example University"]), + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[1, 2]), ), patch( "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", new=AsyncMock(return_value=[]), @@ -307,8 +484,8 @@ async def test_top_authors_combines_dfg_involved_people_case_insensitively(): result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") assert [author.model_dump() for author in result.projects] == [ - {"id": "A1", "name": "Ada Example", "count": 5}, - {"id": None, "name": "DFG Person", "count": 4}, + {"id": "A1", "name": "Ada Example", "count": 1}, + {"id": None, "name": "DFG Person", "count": 1}, ] diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 4b827cb2..25d79648 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -178,7 +178,7 @@

Top 10 Personen aller Zeiten

-

Nach Anzahl der Works, Patente und News Ihrer Organisation.

+

Nach Anzahl der Works, DFG-Projekte, Patente und News Ihrer Organisation.

diff --git a/webapp/src/app/modules/dashboard/dashboard.component.scss b/webapp/src/app/modules/dashboard/dashboard.component.scss index 565fa58f..278954d9 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.scss +++ b/webapp/src/app/modules/dashboard/dashboard.component.scss @@ -303,8 +303,10 @@ margin-bottom: 0.25rem; font-size: 0.85rem; - span { + .author-name { overflow: hidden; + color: #1d4ed8; + font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } @@ -312,8 +314,6 @@ .author-link { overflow: hidden; - color: #1d4ed8; - font-weight: 600; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index ea16ab26..22c575ea 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -24,6 +24,12 @@ type TopicTreemapPeriod = | 'last_10_years' | 'all_time' | 'custom'; +type TopAuthorDataset = { + title: string; + icon: string; + entries: TopAuthor[]; + stripAuthorTitle?: boolean; +}; @Component({ selector: 'dashboard', @@ -94,11 +100,7 @@ export class DashboardComponent implements OnInit { return this.statisticLoading[key]; } - topAuthorDatasets(): Array<{ - title: string; - icon: string; - entries: TopAuthor[]; - }> { + topAuthorDatasets(): TopAuthorDataset[] { return [ { title: 'Publikationen', @@ -110,15 +112,17 @@ export class DashboardComponent implements OnInit { icon: 'description', entries: this.topAuthors?.patents ?? [], }, + { + title: 'DFG Projekte', + icon: 'account_tree', + entries: this.topAuthors?.projects ?? [], + stripAuthorTitle: true, + }, { title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] }, ]; } - visibleTopAuthorDatasets(): Array<{ - title: string; - icon: string; - entries: TopAuthor[]; - }> { + visibleTopAuthorDatasets(): TopAuthorDataset[] { const datasets = this.topAuthorDatasets(); return this.topAuthorsLoading ? datasets @@ -149,6 +153,19 @@ export class DashboardComponent implements OnInit { return (count / maximum) * 100; } + authorDisplayName(dataset: TopAuthorDataset, entry: TopAuthor): string { + if (!dataset.stripAuthorTitle) return entry.name; + + return ( + entry.name + .replace( + /^(?:(?:(?:apl\.\s*)?prof(?:essor)?\.?|priv\.-doz\.?|pd|dr\.?)\s+)+/i, + '', + ) + .trim() || entry.name + ); + } + organizationName(): string { return this.statistics?.organization_name ?? 'Ihre Organisation'; } From fc134dad8eb0651a749556e64efc910f972af0d9 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Wed, 22 Jul 2026 23:46:23 +0200 Subject: [PATCH 02/15] Update DFG project test --- .../src/main/inse/dashboard/test_service.py | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 8244e305..b2bbd0f0 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,6 +9,7 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( + DFG_INSTITUTION_FIELDS, get_dashboard_organization, get_dashboard_statistics, get_top_authors, @@ -230,18 +231,35 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): for call in mocked_search.await_args_list if call.kwargs["index"] == ESIndex.DFG_PROJECTS ] - assert len(dfg_project_calls) == 1 assert dfg_project_calls[0].kwargs["body"]["_source"] == [ - "id", - "project_id", - "persons", + "id", + "project_id", + "persons", + *DFG_INSTITUTION_FIELDS, ] - assert dfg_project_calls[0].kwargs["body"]["query"] == { - "nested": { - "path": "persons", - "query": {"terms": {"persons.person_id": [2]}}, - } + + query = dfg_project_calls[0].kwargs["body"]["query"] + + assert query["bool"]["must"][0]["bool"]["minimum_should_match"] == 1 + assert query["bool"]["must"][0]["bool"]["should"][0]["bool"]["should"][0][ + "match" + ] == { + "Antragstellende Institution": { + "query": "Example Org", + "operator": "and", } +} + + assert query["bool"]["must"][1] == { + "nested": { + "path": "persons", + "query": { + "terms": { + "persons.person_id": [2], + } + }, + } +} @pytest.mark.anyio From 3d78ec900e88db0028cae40e15fae71f04da16e9 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Thu, 23 Jul 2026 01:06:44 +0200 Subject: [PATCH 03/15] Fix DFG top authors aggregation --- service/src/main/inse/dashboard/service.py | 32 ++++---------- .../src/main/inse/dashboard/test_service.py | 44 +++++++------------ 2 files changed, 23 insertions(+), 53 deletions(-) diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index a491c51f..ee4e11e6 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -660,7 +660,6 @@ async def _top_project_authors( page=page, size=size, person_ids=selected_person_ids, - aliases=aliases, ) if not project_hits: @@ -781,7 +780,6 @@ async def _dfg_project_author_hits( page: int, size: int, person_ids: set[int], - aliases: list[str], ) -> tuple[list[dict[str, Any]], int]: response = await elasticsearch.search( index=ESIndex.DFG_PROJECTS, @@ -792,27 +790,13 @@ async def _dfg_project_author_hits( "id", "project_id", "persons", - *DFG_INSTITUTION_FIELDS, ], "query": { - "bool": { - "must": [ - - _dfg_institution_query(aliases), - - { - "nested": { - "path": "persons", - "query": { - "terms": { - "persons.person_id": sorted( - person_ids - ) - } - }, - } - }, - ] + "nested": { + "path": "persons", + "query": { + "terms": {"persons.person_id": sorted(person_ids)} + }, } }, "sort": [ @@ -853,9 +837,9 @@ async def _dfg_project_author_hits( return hits, total def _dfg_project_id(project: dict[str, Any]) -> str | None: - project_id = project.get("project_id") + project_id = project.get("id") if project_id is None: - project_id = project.get("id") + project_id = project.get("project_id") return str(project_id) if project_id is not None else None @@ -911,4 +895,4 @@ async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]: ) for bucket in buckets if str(bucket.get("key", "")).casefold() in institution_authors - ][:TOP_AUTHOR_LIMIT] \ No newline at end of file + ][:TOP_AUTHOR_LIMIT] diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index b2bbd0f0..1e053c92 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -9,7 +9,6 @@ from sqlmodel import Session, SQLModel, create_engine from inse import config from inse.auth.model import AccessToken, Organization, UserRole from inse.dashboard.service import ( - DFG_INSTITUTION_FIELDS, get_dashboard_organization, get_dashboard_statistics, get_top_authors, @@ -141,7 +140,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): { "_source": { "id": "ES1", - "project_id": "P1", + "project_id": "legacy-P1", "persons": [ {"person_id": 2, "full_name": "Grace Example"}, { @@ -154,7 +153,7 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): { "_source": { "id": "ES2", - "project_id": "P2", + "project_id": "legacy-P2a", "persons": [ {"person_id": 2, "full_name": "Grace Example"}, {"person_id": 2, "full_name": "Grace Example"}, @@ -163,8 +162,8 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): }, { "_source": { - "id": "ES3", - "project_id": "P2", + "id": "ES2", + "project_id": "legacy-P2b", "persons": [ {"person_id": 2, "full_name": "Grace Example"}, ], @@ -232,34 +231,21 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): if call.kwargs["index"] == ESIndex.DFG_PROJECTS ] assert dfg_project_calls[0].kwargs["body"]["_source"] == [ - "id", - "project_id", - "persons", - *DFG_INSTITUTION_FIELDS, + "id", + "project_id", + "persons", ] - query = dfg_project_calls[0].kwargs["body"]["query"] - - assert query["bool"]["must"][0]["bool"]["minimum_should_match"] == 1 - assert query["bool"]["must"][0]["bool"]["should"][0]["bool"]["should"][0][ - "match" - ] == { - "Antragstellende Institution": { - "query": "Example Org", - "operator": "and", - } -} - - assert query["bool"]["must"][1] == { - "nested": { - "path": "persons", - "query": { - "terms": { - "persons.person_id": [2], - } + assert dfg_project_calls[0].kwargs["body"]["query"] == { + "nested": { + "path": "persons", + "query": { + "terms": { + "persons.person_id": [2], + } + }, }, } -} @pytest.mark.anyio From 2d485263d1c444ae01635e1a9c83ec0dd4d0d63a Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 24 Jul 2026 11:31:25 +0200 Subject: [PATCH 04/15] Improve DFG top author OpenAlex matching --- service/src/main/inse/dashboard/model.py | 1 + service/src/main/inse/dashboard/service.py | 295 +++++++++++++++++- .../src/main/inse/dashboard/test_service.py | 259 ++++++++++++++- 3 files changed, 545 insertions(+), 10 deletions(-) diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index c59f8028..bbd9f1b2 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -20,6 +20,7 @@ class DashboardStatisticValue(BaseModel): class TopAuthor(BaseModel): id: str | None = None + dfg_person_id: int | None = None name: str count: int diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index ee4e11e6..93cdcea8 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -1,5 +1,6 @@ import asyncio import logging +import re from datetime import datetime from typing import Any, Literal @@ -30,6 +31,10 @@ TOPIC_HEATMAP_LIMIT = 25 TOPIC_HEATMAP_YEARS = 5 WorksPeriod = Literal["all_time", "last_5_years"] logger = logging.getLogger(__name__) +ACADEMIC_TITLE_RE = re.compile( + r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+", + re.IGNORECASE, +) DFG_INSTITUTION_FIELDS = [ "Antragstellende Institution", @@ -50,6 +55,34 @@ def _total(response: dict[str, Any]) -> int: return int(total or 0) +def _normalize_person_name(name: str) -> str: + normalized = " ".join(name.strip().casefold().split()) + while True: + without_title = ACADEMIC_TITLE_RE.sub("", normalized).strip() + if without_title == normalized: + return without_title + normalized = without_title + + +def _is_initial_surname_match(full_name: str, initial_name: str) -> bool: + full_parts = _normalize_person_name(full_name).split() + initial_parts = _normalize_person_name(initial_name).replace(".", "").split() + if len(full_parts) < 2 or len(initial_parts) < 2: + return False + return ( + len(initial_parts[0]) == 1 + and full_parts[0].startswith(initial_parts[0]) + and full_parts[-1] == initial_parts[-1] + ) + + +def _is_supported_name_variant(full_name: str, candidate_name: str) -> bool: + return ( + _normalize_person_name(full_name) == _normalize_person_name(candidate_name) + or _is_initial_surname_match(full_name, candidate_name) + ) + + def get_dashboard_organization( session: Session, access_token: AccessToken, @@ -709,11 +742,13 @@ async def _top_project_authors( page += 1 - institution_authors = { - author["name"].strip().casefold(): author - for author in authors - if author.get("name") - } + institution_authors: dict[str, list[dict[str, Any]]] = {} + for author in authors: + if author.get("name"): + institution_authors.setdefault( + _normalize_person_name(author["name"]), + [], + ).append(author) ranked = sorted( ( @@ -727,14 +762,33 @@ async def _top_project_authors( ), ) + ranked_person_ids = [person_id for person_id, _ in ranked[:TOP_AUTHOR_LIMIT]] + dfg_orcids = await _dfg_person_orcids(ranked_person_ids) + result: list[TopAuthor] = [] for person_id, project_ids in ranked[:TOP_AUTHOR_LIMIT]: dfg_name = names[person_id] - matched_author = institution_authors.get( - dfg_name.casefold() + matched_author = _single_author_match( + institution_authors.get(_normalize_person_name(dfg_name), []) ) + if matched_author is None and (orcid := dfg_orcids.get(person_id)): + matched_author = await _openalex_author_by_orcid(orcid) + + if matched_author is None: + matched_author = await _openalex_author_by_dfg_publication_evidence( + dfg_name=dfg_name, + project_ids=project_ids, + ) + + if matched_author is None: + logger.info( + "No exact OpenAlex match for DFG author '%s' (person_id=%s).", + dfg_name, + person_id, + ) + result.append( TopAuthor( id=( @@ -742,6 +796,7 @@ async def _top_project_authors( if matched_author else None ), + dfg_person_id=person_id, name=( matched_author["name"] if matched_author @@ -767,6 +822,230 @@ async def _top_project_authors( return result +def _single_author_match(authors: list[dict[str, Any]]) -> dict[str, Any] | None: + return authors[0] if len(authors) == 1 else None + + +async def _dfg_person_orcids(person_ids: list[int]) -> dict[int, str]: + if not person_ids: + return {} + + try: + response = await elasticsearch.search( + index=ESIndex.DFG_PERSONS, + body={ + "size": len(person_ids), + "_source": ["person_id", "orcid_id"], + "query": {"terms": {"person_id": person_ids}}, + }, + cluster=ESCluster.INSE, + ) + except Exception: + logger.exception("Could not load DFG ORCIDs for top project authors.") + return {} + + result: dict[int, str] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + person_id = source.get("person_id") + orcid = source.get("orcid_id") + if person_id is None or not orcid: + continue + try: + result[int(person_id)] = str(orcid) + except (TypeError, ValueError): + continue + return result + + +async def _openalex_author_by_orcid(orcid: str) -> dict[str, Any] | None: + normalized_orcid = orcid.replace("https://orcid.org/", "").strip() + if not normalized_orcid: + return None + + prefixed_orcid = f"https://orcid.org/{normalized_orcid}" + try: + response = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + body={ + "size": 2, + "_source": ["id", "display_name"], + "query": { + "bool": { + "should": [ + {"term": {"orcid.keyword": normalized_orcid}}, + {"term": {"orcid.keyword": prefixed_orcid}}, + {"term": {"ids.orcid.keyword": normalized_orcid}}, + {"term": {"ids.orcid.keyword": prefixed_orcid}}, + {"term": {"orcid": normalized_orcid}}, + {"term": {"orcid": prefixed_orcid}}, + {"term": {"ids.orcid": normalized_orcid}}, + {"term": {"ids.orcid": prefixed_orcid}}, + ], + "minimum_should_match": 1, + } + }, + }, + cluster=ESCluster.NES, + track_total_hits=True, + ) + except Exception: + logger.exception("Could not resolve OpenAlex author by ORCID %s.", orcid) + return None + + hits = response.get("hits", {}).get("hits", []) + if len(hits) != 1: + logger.info( + "OpenAlex ORCID lookup for %s returned %s hits.", + orcid, + len(hits), + ) + return None + + source = hits[0].get("_source", {}) + if not source.get("id") or not source.get("display_name"): + return None + return { + "id": str(source["id"]), + "name": str(source["display_name"]), + } + + +async def _openalex_author_by_dfg_publication_evidence( + dfg_name: str, + project_ids: set[str], +) -> dict[str, Any] | None: + dois = await _dfg_project_publication_dois(project_ids) + if not dois: + return None + + try: + response = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body={ + "size": 10000, + "_source": [ + "doi", + "authorships.author.id", + "authorships.author.display_name", + ], + "query": { + "terms": { + "doi": sorted(_doi_variants(dois)), + } + }, + }, + cluster=ESCluster.NES, + ) + except Exception: + logger.exception( + "Could not resolve OpenAlex author from DFG publication DOIs for %s.", + dfg_name, + ) + return None + + candidates: dict[str, dict[str, Any]] = {} + for hit in response.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + doi = source.get("doi") + if not doi: + continue + for authorship in source.get("authorships", []) or []: + author = authorship.get("author", {}) if isinstance(authorship, dict) else {} + author_id = author.get("id") + display_name = author.get("display_name") + if not author_id or not display_name: + continue + if not _is_supported_name_variant(dfg_name, str(display_name)): + continue + candidate = candidates.setdefault( + str(author_id), + { + "id": str(author_id), + "name": str(display_name), + "dois": set(), + }, + ) + candidate["dois"].add(str(doi)) + + supported_candidates = [ + candidate + for candidate in candidates.values() + if len(candidate["dois"]) >= 2 + ] + if len(supported_candidates) != 1: + if supported_candidates: + logger.info( + "DFG publication DOI lookup for %s returned %s candidates.", + dfg_name, + len(supported_candidates), + ) + return None + + candidate = supported_candidates[0] + return { + "id": candidate["id"], + "name": candidate["name"], + } + + +async def _dfg_project_publication_dois(project_ids: set[str]) -> set[str]: + if not project_ids: + return set() + + numeric_project_ids = [ + int(project_id) + for project_id in project_ids + if str(project_id).isdigit() + ] + if not numeric_project_ids: + return set() + + try: + response = await elasticsearch.search( + index=ESIndex.DFG_PROJECTS, + body={ + "size": len(numeric_project_ids), + "_source": ["publications.doi"], + "query": {"terms": {"id": numeric_project_ids}}, + }, + cluster=ESCluster.INSE, + ) + except Exception: + logger.exception("Could not load DFG publication DOIs.") + return set() + + dois: set[str] = set() + for hit in response.get("hits", {}).get("hits", []): + for publication in hit.get("_source", {}).get("publications", []) or []: + doi = publication.get("doi") if isinstance(publication, dict) else None + if doi: + dois.add(str(doi).strip()) + return {doi for doi in dois if doi} + + +def _doi_variants(dois: set[str]) -> set[str]: + variants: set[str] = set() + for doi in dois: + normalized = doi.strip() + if not normalized: + continue + raw = normalized + for prefix in ("https://doi.org/", "http://dx.doi.org/"): + if raw.casefold().startswith(prefix): + raw = raw[len(prefix):] + break + variants.update( + { + normalized, + normalized.lower(), + f"https://doi.org/{raw}", + f"https://doi.org/{raw.lower()}", + } + ) + return variants + + async def _dfg_institution_ids_for_organization(organization_name: str) -> list[int]: page = await autocomplete_institutions_for_selector( query=organization_name, @@ -797,7 +1076,7 @@ async def _dfg_project_author_hits( "query": { "terms": {"persons.person_id": sorted(person_ids)} }, - } + }, }, "sort": [ { diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 1e053c92..ae0a99a4 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -202,21 +202,25 @@ async def test_top_authors_maps_works_and_dfg_project_aggregations(): assert result.works[0].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 42, } assert result.projects[0].model_dump() == { "id": "A2", + "dfg_person_id": 2, "name": "Grace Example", "count": 2, } assert result.patents[0].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 4, } assert result.news[0].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 6, } @@ -294,6 +298,7 @@ async def test_top_authors_keeps_dfg_project_authors_without_openalex_match(): assert result.projects[0].model_dump() == { "id": None, + "dfg_person_id": 9, "name": "Project Person", "count": 9, } @@ -363,6 +368,7 @@ async def test_top_authors_processes_all_dfg_project_pages(): assert result.projects[0].model_dump() == { "id": None, + "dfg_person_id": 9, "name": "Project Person", "count": 10001, } @@ -488,8 +494,255 @@ async def test_top_authors_matches_dfg_project_people_to_openalex_case_insensiti result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") assert [author.model_dump() for author in result.projects] == [ - {"id": "A1", "name": "Ada Example", "count": 1}, - {"id": None, "name": "DFG Person", "count": 1}, + {"id": "A1", "dfg_person_id": 1, "name": "Ada Example", "count": 1}, + {"id": None, "dfg_person_id": 2, "name": "DFG Person", "count": 1}, + ] + + +@pytest.mark.anyio +async def test_top_authors_links_dfg_project_people_by_title_stripped_name_or_orcid(): + async def search(**kwargs): + if kwargs["index"] == config.settings.openalex_works_search_index: + return { + "hits": { + "hits": [ + { + "_source": { + "doi": "https://doi.org/10.1/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5056038758", + "display_name": "G. Bacher", + } + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.2/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5056038758", + "display_name": "G. Bacher", + } + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.3/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5025875670", + "display_name": "Stephan Barcikowski", + } + } + ], + } + }, + { + "_source": { + "doi": "https://doi.org/10.4/example", + "authorships": [ + { + "author": { + "id": "https://openalex.org/A5025875670", + "display_name": "Stephan Barcikowski", + } + } + ], + } + }, + ] + } + } + if kwargs["index"] == ESIndex.OPENALEX_AUTHORS: + if kwargs.get("query") is not None: + return { + "hits": { + "hits": [ + { + "_source": { + "id": "https://openalex.org/A3", + "display_name": "Stephan Schulz", + "works_count": 1, + "counts_by_year": [], + } + } + ] + } + } + return { + "hits": { + "hits": [ + { + "_source": { + "id": "https://openalex.org/A5068103398", + "display_name": "U. Bovensiepen", + } + } + ] + } + } + if kwargs["index"] == ESIndex.DFG_PERSONS: + return { + "hits": { + "hits": [ + { + "_source": { + "person_id": 1, + "orcid_id": "0000-0002-1506-4491", + } + }, + { + "_source": { + "person_id": 3, + "orcid_id": "0000-0003-2896-4488", + } + }, + ] + } + } + if kwargs["index"] == ESIndex.DFG_PROJECTS: + if kwargs["body"].get("_source") == ["publications.doi"]: + return { + "hits": { + "hits": [ + { + "_source": { + "publications": [ + {"doi": "https://doi.org/10.1/example"} + ] + } + }, + { + "_source": { + "publications": [ + {"doi": "https://doi.org/10.2/example"} + ] + } + }, + { + "_source": { + "publications": [ + {"doi": "https://doi.org/10.3/example"}, + {"doi": "https://doi.org/10.4/example"}, + ] + } + }, + ] + } + } + return { + "hits": { + "total": {"value": 3}, + "hits": [ + { + "_source": { + "id": 1, + "project_id": None, + "persons": [ + { + "person_id": 1, + "full_name": "Professor Dr. Uwe Bovensiepen", + }, + { + "person_id": 2, + "full_name": "Professor Dr. Gerd Bacher", + }, + { + "person_id": 3, + "full_name": "Professor Dr. Stephan Schulz", + }, + { + "person_id": 4, + "full_name": "Professor Dr.-Ing. Stephan Barcikowski", + }, + ], + } + }, + { + "_source": { + "id": 2, + "project_id": None, + "persons": [ + { + "person_id": 1, + "full_name": "Professor Dr. Uwe Bovensiepen", + }, + { + "person_id": 2, + "full_name": "Professor Dr. Gerd Bacher", + }, + ], + } + }, + { + "_source": { + "id": 3, + "project_id": None, + "persons": [ + { + "person_id": 1, + "full_name": "Professor Dr. Uwe Bovensiepen", + }, + ], + } + }, + ], + } + } + return {"aggregations": {"authors": {"buckets": []}}} + + with patch( + "inse.dashboard.service.elasticsearch.search", + new=AsyncMock(side_effect=search), + ), patch( + "inse.dashboard.service.autocomplete_institutions_for_selector", + new=AsyncMock( + return_value=SimpleNamespace( + elements=[SimpleNamespace(id=101)] + ) + ), + ), patch( + "inse.dashboard.service.get_person_ids_by_institution_ids", + new=AsyncMock(return_value=[1, 2, 3, 4]), + ), patch( + "inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution", + new=AsyncMock(return_value=[]), + ): + result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org") + + assert [author.model_dump() for author in result.projects] == [ + { + "id": "A5068103398", + "dfg_person_id": 1, + "name": "U. Bovensiepen", + "count": 3, + }, + { + "id": "A5056038758", + "dfg_person_id": 2, + "name": "G. Bacher", + "count": 2, + }, + { + "id": "A3", + "dfg_person_id": 3, + "name": "Stephan Schulz", + "count": 1, + }, + { + "id": "A5025875670", + "dfg_person_id": 4, + "name": "Stephan Barcikowski", + "count": 1, + }, ] @@ -585,11 +838,13 @@ async def test_top_authors_can_rank_works_by_last_five_years(): assert result.works[0].model_dump() == { "id": "A2", + "dfg_person_id": None, "name": "Grace Example", "count": 16, } assert result.works[1].model_dump() == { "id": "A1", + "dfg_person_id": None, "name": "Ada Example", "count": 2, } From 0b5c6bed37cfad3f3fb71c12196af64d23323416 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 24 Jul 2026 11:31:55 +0200 Subject: [PATCH 05/15] Use DFG person IDs for project --- .../inse/projects/projects_search_client.py | 12 ++++ service/src/main/inse/projects/service.py | 15 +---- .../main/inse/projects/test_projects_dfg.py | 60 +++++++++++++++++++ 3 files changed, 74 insertions(+), 13 deletions(-) diff --git a/service/src/main/inse/projects/projects_search_client.py b/service/src/main/inse/projects/projects_search_client.py index 3a0a7557..3f5911d2 100644 --- a/service/src/main/inse/projects/projects_search_client.py +++ b/service/src/main/inse/projects/projects_search_client.py @@ -584,6 +584,7 @@ async def search_dfg_projects( page: int, size: int, institution_ids: Optional[List[int]] = None, + person_ids: Optional[List[int]] = None, names: Optional[List[str]] = None, keywords: Optional[List[str]] = None, topic_ids: Optional[List[str]] = None, @@ -601,6 +602,7 @@ async def search_dfg_projects( page (int): The page number. size (int): The number of items per page. institution_ids (Optional[List[int]], optional): Institution IDs to filter by. + person_ids (Optional[List[int]], optional): Person IDs to filter by. names (Optional[List[str]], optional): Names to search for. keywords (Optional[List[str]], optional): Raw keywords to search in title/abstract/subject fields. Only used when `fuzzy=False` (or when no topic_ids are given). @@ -742,6 +744,16 @@ async def search_dfg_projects( if name_must_clauses: must_clauses.append({"bool": {"must": name_must_clauses}}) + if person_ids: + must_clauses.append( + { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": person_ids}}, + } + } + ) + if institution_ids: matching_person_ids = await get_person_ids_by_institution_ids( institution_ids=institution_ids diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 86637a6f..7cf83d11 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -26,7 +26,7 @@ from inse.institutions.institutions_search_client import ( ) from inse.exceptions import NotFoundException from inse.persons.logic import get_author_name_by_id -from inse.projects.logic import get_dfg_author_names_by_ids, get_dfg_institution_names_by_ids +from inse.projects.logic import get_dfg_institution_names_by_ids from inse.works.logic import get_publication_dois_of_author from inse.models.projects_eu_cordis.horizon2020.h2020_project_details import H2020ProjectDetails from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails @@ -192,17 +192,6 @@ async def get_dfg_projects_by_author_id( if author_id and not author_name: logger.debug("No author name found for author_id=%s", author_id) - filter_names = ( - await get_dfg_author_names_by_ids(author_ids=author_filter_ids) - if author_filter_ids - else [] - ) - if author_filter_ids and not filter_names: - logger.debug( - "No author names found for author_filter_ids=%s", - author_filter_ids, - ) - if author_name: filter_names.append(author_name) @@ -216,6 +205,7 @@ async def get_dfg_projects_by_author_id( page=page, size=size, names=filter_names or [], + person_ids=author_filter_ids or [], institution_ids=institution_ids, keywords=keywords, topic_ids=topic_ids, @@ -413,4 +403,3 @@ async def search_cordis_eu_projects_for_author_id( ) return funding_project_page - diff --git a/service/src/main/inse/projects/test_projects_dfg.py b/service/src/main/inse/projects/test_projects_dfg.py index 801859e6..3b83eae7 100644 --- a/service/src/main/inse/projects/test_projects_dfg.py +++ b/service/src/main/inse/projects/test_projects_dfg.py @@ -1,4 +1,8 @@ +from unittest.mock import AsyncMock, patch + import pytest + +from inse.model import ESCluster, ESIndex from inse.projects import projects_search_client @pytest.mark.anyio @@ -35,3 +39,59 @@ async def test_get_dfg_project_by_id(): "Leibniz" in inst for inst in project.institutions ) + + +@pytest.mark.anyio +async def test_search_dfg_projects_filters_directly_by_person_ids(): + mocked_search = AsyncMock( + return_value={ + "hits": { + "total": {"value": 1}, + "hits": [ + { + "_id": "P1", + "_source": { + "id": "P1", + "title": "Example project", + "persons": [ + { + "person_id": 1739927, + "full_name": "Professor Dr. Uwe Bovensiepen", + } + ], + "subject_classifications": [], + }, + } + ], + } + } + ) + + with patch( + "inse.projects.projects_search_client.elasticsearch.search", + new=mocked_search, + ), patch( + "inse.projects.projects_search_client.get_openalex_topics_for_dfg_projects", + new=AsyncMock(return_value={}), + ), patch( + "inse.projects.projects_search_client.get_person_institutes", + new=AsyncMock(return_value={}), + ): + result = await projects_search_client.search_dfg_projects( + page=0, + size=10, + person_ids=[1739927], + ) + + assert result.total == 1 + call = mocked_search.await_args + assert call.kwargs["index"] == ESIndex.DFG_PROJECTS + assert call.kwargs["cluster"] == ESCluster.INSE + assert call.kwargs["body"]["query"]["bool"]["must"] == [ + { + "nested": { + "path": "persons", + "query": {"terms": {"persons.person_id": [1739927]}}, + } + } + ] From f25c5cd22267589a02dc72cf3b105433786975c5 Mon Sep 17 00:00:00 2001 From: spsaefan <117728614+spsaefan@users.noreply.github.com> Date: Fri, 24 Jul 2026 11:32:14 +0200 Subject: [PATCH 06/15] Link DFG top authors to person pages --- webapp/src/app/api/model/topAuthor.ts | 2 +- .../dashboard/dashboard-statistics.service.ts | 1 + .../dashboard/dashboard.component.html | 3 +- .../modules/dashboard/dashboard.component.ts | 28 +++++++++++++++++++ 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/api/model/topAuthor.ts b/webapp/src/app/api/model/topAuthor.ts index 6a74fa91..8171a2af 100644 --- a/webapp/src/app/api/model/topAuthor.ts +++ b/webapp/src/app/api/model/topAuthor.ts @@ -11,7 +11,7 @@ export interface TopAuthor { id?: string | null; + dfg_person_id?: number | null; name: string; count: number; } - diff --git a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts index 828fd7ee..6cdd29f1 100644 --- a/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts +++ b/webapp/src/app/modules/dashboard/dashboard-statistics.service.ts @@ -25,6 +25,7 @@ export interface DashboardStatisticValue { export interface TopAuthor { id?: string | null; + dfg_person_id?: number | null; name: string; count: number; } diff --git a/webapp/src/app/modules/dashboard/dashboard.component.html b/webapp/src/app/modules/dashboard/dashboard.component.html index 25d79648..30b8febd 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.html +++ b/webapp/src/app/modules/dashboard/dashboard.component.html @@ -220,7 +220,8 @@ @if (entry.id) { {{ authorDisplayName(dataset, entry) }} diff --git a/webapp/src/app/modules/dashboard/dashboard.component.ts b/webapp/src/app/modules/dashboard/dashboard.component.ts index 22c575ea..3d78b84e 100644 --- a/webapp/src/app/modules/dashboard/dashboard.component.ts +++ b/webapp/src/app/modules/dashboard/dashboard.component.ts @@ -29,6 +29,7 @@ type TopAuthorDataset = { icon: string; entries: TopAuthor[]; stripAuthorTitle?: boolean; + projectAuthors?: boolean; }; @Component({ @@ -117,6 +118,7 @@ export class DashboardComponent implements OnInit { icon: 'account_tree', entries: this.topAuthors?.projects ?? [], stripAuthorTitle: true, + projectAuthors: true, }, { title: 'News', icon: 'article', entries: this.topAuthors?.news ?? [] }, ]; @@ -166,6 +168,32 @@ export class DashboardComponent implements OnInit { ); } + authorLink(dataset: TopAuthorDataset, entry: TopAuthor): string[] { + if (dataset.projectAuthors && entry.dfg_person_id) { + return ['/person', entry.id!, 'projects']; + } + + return ['/person', entry.id!, 'overview']; + } + + authorQueryParams( + dataset: TopAuthorDataset, + entry: TopAuthor, + ): Record | null { + if (!dataset.projectAuthors || !entry.dfg_person_id) { + return null; + } + + return { + project_type: 'dfg', + page: 0, + size: 10, + sort_by: 'title', + sort_direction: 'asc', + authorId: entry.dfg_person_id, + }; + } + organizationName(): string { return this.statistics?.organization_name ?? 'Ihre Organisation'; } From 652ff8db154277c271a900731c7a3254836f1088 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 18:39:08 +0200 Subject: [PATCH 07/15] changed news trend search to use new index & added test for top 20 news search --- service/src/main/inse/model.py | 1 + .../test_trend_strategies.py | 13 ++ .../inse/university_ranking/trend_logic.py | 112 ++++++++++++++---- .../university_ranking/trend_strategies.py | 83 +++++++------ 4 files changed, 149 insertions(+), 60 deletions(-) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index f5a0f79e..039a1367 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -68,6 +68,7 @@ class ESIndex(StrEnum): AKTUELLES = "aktuell" AKTUELLES_POSTPROC = "aktuell_postproc" + AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics" CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations" diff --git a/service/src/main/inse/university_ranking/test_trend_strategies.py b/service/src/main/inse/university_ranking/test_trend_strategies.py index e4c063ef..b8bd8f9d 100644 --- a/service/src/main/inse/university_ranking/test_trend_strategies.py +++ b/service/src/main/inse/university_ranking/test_trend_strategies.py @@ -170,6 +170,19 @@ async def test_get_top_topics_for_entity_projects(): assert "items" in res +@pytest.mark.anyio +async def test_get_top_topics_for_entity_news(): + res = await get_top_topics_for_entity( + entity_id="UDE", + entity_type="institution", + start_year=2018, + end_year=2024, + search_type="news", + ) + assert isinstance(res, dict) + assert "items" in res + + @pytest.mark.anyio async def test_get_trend_data_delegation(): res = await get_trend_data( diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 753fb4a7..585ba653 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -456,31 +456,99 @@ async def get_top_topics_for_entity( if search_type == "news": try: - res = await elasticsearch.search( - index=ESIndex.AKTUELLES_POSTPROC.value, - body={ - "query": {"match_all": {}}, - "size": 0, - "_source": False, - "aggs": { - "top_topics": { - "terms": { - "field": "topics.display_name.keyword", - "size": DEFAULT_TOP_TOPICS_SIZE, + date_filter = TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year) + news_ids = [] + try: + async for hit in elasticsearch.scan( + index=ESIndex.AKTUELLES.value, + query={"bool": {"filter": [date_filter]}}, + source=["news_id"], + cluster=ESCluster.INSE, + ): + nid = hit.get("_id") or hit.get("_source", {}).get("news_id") + if nid: + news_ids.append(str(nid)) + except Exception as e: + logger.warning("Failed scanning aktuell for news IDs in date range: %s", e) + + topic_counts: Dict[str, int] = {} + if news_ids: + msearch_queries = [] + for i in range(0, len(news_ids), 2000): + chunk = news_ids[i : i + 2000] + payload = { + "query": { + "bool": { + "should": [ + {"ids": {"values": chunk}}, + {"terms": {"news_id.keyword": chunk}}, + {"terms": {"news_id": chunk}}, + ], + "minimum_should_match": 1, } - } - }, - }, - cluster=ESCluster.INSE, - ) - buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) - items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets] - total_hits = res.get("hits", {}).get("total", {}) - total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0) - sum_top = sum(b["count"] for b in items) - other_count = max(0, total_val - sum_top) + }, + "size": 0, + "_source": False, + "aggs": { + "top_topics": { + "terms": { + "field": "topic_matches.topic_display_name.keyword", + "size": 100, + } + } + }, + } + msearch_queries.append((ESIndex.AKTUELLES_OPENALEX_TOPICS.value, payload)) + + if msearch_queries: + try: + responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE) + for res in responses: + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + for b in buckets: + t_name = b["key"] + cnt = b["doc_count"] + topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt + except Exception as e: + logger.warning("Failed to aggregate news top topics via msearch: %s", e) + else: + # If no year filter bounds active or scan returned no IDs, aggregate all topics directly from openalex_topics + try: + res = await elasticsearch.search( + index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, + body={ + "query": {"match_all": {}}, + "size": 0, + "_source": False, + "aggs": { + "top_topics": { + "terms": { + "field": "topic_matches.topic_display_name.keyword", + "size": 100, + } + } + }, + }, + cluster=ESCluster.INSE, + ) + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + for b in buckets: + t_name = b["key"] + cnt = b["doc_count"] + topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt + except Exception as e: + logger.warning("Failed to fallback query news top topics: %s", e) + + sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True) + top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE] + items = [{"name": name, "count": count} for name, count in top_slice] + + sum_top = sum(count for name, count in top_slice) + total_topics = sum(topic_counts.values()) + other_count = max(0, total_topics - sum_top) if other_count > 0: items.append({"name": "Andere Themen", "count": other_count}) + return {"items": items} except Exception as e: logger.error("Failed to query top news topics for entity: %s", e) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index d313d49b..e6277f34 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -1066,11 +1066,24 @@ class NewsTrendStrategy(TrendStrategy): STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"} - # Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs + # Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]: + news_ids: Set[str] = set() if fuzzy: term = t_name - es_query = {"match": {"topics.display_name": term}} + es_query = {"term": {"topic_matches.topic_display_name.keyword": term}} + try: + async for hit in elasticsearch.scan( + index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value, + query=es_query, + source=["news_id"], + cluster=ESCluster.INSE, + ): + nid = hit.get("_source", {}).get("news_id") or hit.get("_id") + if nid: + news_ids.add(str(nid)) + except Exception as e: + logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e) else: if keywords and idx < len(keywords) and keywords[idx]: raw_kw = keywords[idx] @@ -1079,43 +1092,28 @@ class NewsTrendStrategy(TrendStrategy): term = t_name else: term = t_name - es_query = {"match": {"keywords": term}} - news_ids: Set[str] = set() - try: - async for hit in elasticsearch.scan( - index=ESIndex.AKTUELLES_POSTPROC.value, - query=es_query, - source=["news_id"], - cluster=ESCluster.INSE, - ): - nid = hit.get("_source", {}).get("news_id") - if nid: - news_ids.add(nid) - except Exception as e: - logger.warning("Failed to scan UDE news postproc: %s", e) - - # If non-fuzzy keyword search, also search article content fields in 'aktuell' index - if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: - try: - content_query = { - "query_string": { - "query": term, - "fields": AKTUELLES_SEARCH_FIELDS, - "default_operator": "AND", + # If non-fuzzy keyword search, search article content fields in 'aktuell' index + if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1: + try: + content_query = { + "query_string": { + "query": term, + "fields": AKTUELLES_SEARCH_FIELDS, + "default_operator": "AND", + } } - } - async for hit in elasticsearch.scan( - index=ESIndex.AKTUELLES.value, - query=content_query, - source=["news_id"], - cluster=ESCluster.INSE, - ): - nid = hit.get("_id") or hit.get("_source", {}).get("news_id") - if nid: - news_ids.add(nid) - except Exception as e: - logger.warning("Failed to scan UDE news content in aktuell: %s", e) + async for hit in elasticsearch.scan( + index=ESIndex.AKTUELLES.value, + query=content_query, + source=["news_id"], + cluster=ESCluster.INSE, + ): + nid = hit.get("_id") or hit.get("_source", {}).get("news_id") + if nid: + news_ids.add(str(nid)) + except Exception as e: + logger.warning("Failed to scan UDE news content in aktuell: %s", e) return list(news_ids) @@ -1134,7 +1132,16 @@ class NewsTrendStrategy(TrendStrategy): "query": { "bool": { "filter": [ - {"ids": {"values": chunk}}, + { + "bool": { + "should": [ + {"ids": {"values": chunk}}, + {"terms": {"news_id.keyword": chunk}}, + {"terms": {"news_id": chunk}}, + ], + "minimum_should_match": 1, + } + }, TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year), ] } From 127c32dce7c4c81abf0778e62356010d3565548f Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 20:05:00 +0200 Subject: [PATCH 08/15] patched missmatch inside news (openalex id vs name) --- .../search-results-state.service.ts | 26 +++++++++++++------ .../uni-trend-parent.component.ts | 19 ++++++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index f9f9dd2d..2401dc97 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -132,14 +132,24 @@ export class SearchResultsStateService { // without a resolvable keyword are skipped when building the lookup map // so they can never collide on an `undefined` key and shadow a real one. readonly topicsList = computed(() => { - const list = this.keywords().map((kw) => { - const entry = this.selectedKeywordEntries().find( - (e) => - e.llm_keyword?.keyword?.trim().toLowerCase() === - kw.trim().toLowerCase(), - ); - return entry?.topic_mapping?.topic?.display_name ?? kw; - }); + const list = this.keywords() + .map((kw) => { + const normalized = kw.trim().toLowerCase(); + const entry = this.selectedKeywordEntries().find( + (e) => + e.llm_keyword?.keyword?.trim().toLowerCase() === normalized || + e.topic_mapping?.topic?.id?.trim().toLowerCase() === normalized, + ); + const displayName = entry?.topic_mapping?.topic?.display_name; + if (displayName && !displayName.startsWith('http')) { + return displayName; + } + if (kw.startsWith('http') || kw.includes('openalex.org/topics')) { + return ''; + } + return kw; + }) + .filter((t) => t.length > 0); return Array.from(new Set(list)); }); diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index dc5a10fd..c14ace0a 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -666,6 +666,25 @@ export class UniTrendParentComponent implements OnInit { ); const resolveEntityName = (s: TrendSeries): string => { + let rawName = s.entity_name || ''; + if (rawName.startsWith('news_topic_')) { + rawName = rawName.slice('news_topic_'.length); + } + if ( + rawName.startsWith('http://') || + rawName.startsWith('https://') || + rawName.includes('openalex.org/topics/') + ) { + const mapped = this.getMappedTopic(rawName); + if (mapped && !mapped.startsWith('http')) { + return mapped; + } + const match = this.state?.topics()?.find((t) => t.id === rawName); + if (match?.display_name) { + return match.display_name; + } + } + const cId = cleanId(s.entity_id); if (s.entity_type === 'institution') { From 7adf12912f564d430f4e5407d49364d0303befd6 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 21:50:02 +0200 Subject: [PATCH 09/15] added resolver preloading and child component state management. (If something breaks in behavior, revert to this point) --- .../uni-trend-parent.component.html | 14 +- .../uni-trend-parent.component.ts | 78 +++++++--- .../src/app/resolvers/uni-trend.resolver.ts | 139 ++++++++++++++++-- 3 files changed, 194 insertions(+), 37 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html index 5766c149..8bf6fe4c 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.html @@ -175,15 +175,15 @@
- @if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) { - - } @else if (rawTrendResponse()) { + @if (rawTrendResponse()) {
+ @if (isTrendLoading() || isPageResolving()) { +
+ +

Daten werden geladen...

+
+ } @if (selectedTrendTopics().length > 0) {
@for (topic of selectedTrendTopics(); track topic) { diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index c14ace0a..91049ea7 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -530,14 +530,23 @@ export class UniTrendParentComponent implements OnInit { if (!res || !res.series || res.series.length === 0) return false; const startYr = this.startYear(); const endYr = this.endYear(); - const mapped = this.getMappedTopic(topic).toLowerCase().trim(); + const topicLower = topic.toLowerCase().trim(); + const mappedLower = this.getMappedTopic(topic).toLowerCase().trim(); return !res.series.some((s) => { - const yearlyList = - s.topic_data?.[topic] || - s.topic_data?.[mapped] || - Object.values(s.topic_data || {})[0]; - if (!yearlyList) return false; + if (!s.topic_data) return false; + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === topicLower || + kLower === mappedLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === topicLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; const total = yearlyList .filter((y) => y.year >= startYr && y.year <= endYr) .reduce((sum, item) => sum + (item.raw || 0), 0); @@ -545,6 +554,12 @@ export class UniTrendParentComponent implements OnInit { }); } + findFirstNonEmptyTopic(topics: string[]): string { + if (!topics || topics.length === 0) return ''; + const nonEmpties = topics.filter((t) => !this.isTopicEmpty(t)); + return nonEmpties.length > 0 ? nonEmpties[0] : topics[0] || ''; + } + isVisible(id: string): boolean { return this.entityVisibilityMap().get(id) !== false; } @@ -892,10 +907,10 @@ export class UniTrendParentComponent implements OnInit { if (resolved.topics && resolved.topics.length > 0) { this.selectedTrendTopics.set(resolved.topics); this.fetchedTopics.set([...resolved.topics]); - const firstNonEmpty = resolved.topics.find( - (t: string) => !this.isTopicEmpty(t), - ); - const targetTopic = firstNonEmpty || resolved.topics[0]; + const targetTopic = + resolved.initialActiveTopic || + resolved.topics.find((t: string) => !this.isTopicEmpty(t)) || + resolved.topics[0]; this.activeChartTopic.set(targetTopic); } else { this.fetchedTopics.set([...this.selectedTrendTopics()]); @@ -929,6 +944,14 @@ export class UniTrendParentComponent implements OnInit { this.fetchedAuthors.set([...this.comparisonAuthors()]); } + if (resolved.topSuggestions) { + this.topSuggestions.set(resolved.topSuggestions); + } + + if (resolved.recommendedAuthors) { + this.recommendedAuthors.set(resolved.recommendedAuthors); + } + if (resolved.treemapData) { this.topicTreemap.set(resolved.treemapData); } @@ -972,11 +995,20 @@ export class UniTrendParentComponent implements OnInit { this.selectedTrendTopics.set(topics); } - // Initialize active chart topic to the first selected topic if empty or invalid + // Initialize active chart topic to a valid non-empty topic const active = currentActive; const updatedSelections = untracked(() => this.selectedTrendTopics()); - if (!active || !updatedSelections.includes(active)) { - this.activeChartTopic.set(updatedSelections[0] || ''); + const mappedActive = this.getMappedTopic(active); + if ( + mappedActive && + updatedSelections.includes(mappedActive) && + !this.isTopicEmpty(mappedActive) + ) { + this.activeChartTopic.set(mappedActive); + } else { + this.activeChartTopic.set( + this.findFirstNonEmptyTopic(updatedSelections), + ); } // If comparison list is empty, initialize default institutions/authors dynamically @@ -1048,7 +1080,11 @@ export class UniTrendParentComponent implements OnInit { : a.id.toLowerCase(); return rawSeriesCleanIds.has(cleanA); }); - } else if (searchType === 'news' || searchType === 'all') { + } else if ( + searchType === 'news' || + searchType === 'all' || + searchType === 'patents' + ) { allEntitiesFetched = true; } else { // publications, patents, projects @@ -1399,7 +1435,11 @@ export class UniTrendParentComponent implements OnInit { if (kws.length === 0) return; const topics = this.state?.topicsList() ?? kws; - const topic = topics[0] || kws[0] || 'Artificial Intelligence'; + const topic = + this.findFirstNonEmptyTopic(topics) || + topics[0] || + kws[0] || + 'Artificial Intelligence'; this.personsApiService .searchPersonsList( @@ -1595,7 +1635,6 @@ export class UniTrendParentComponent implements OnInit { }); } this.isTrendLoading.set(false); - this.updateUrlParams(); }, error: () => { this.isTrendLoading.set(false); @@ -1695,8 +1734,8 @@ export class UniTrendParentComponent implements OnInit { this.selectedTrendTopics.set(updated); const active = this.activeChartTopic(); - if (!updated.includes(active)) { - this.activeChartTopic.set(updated[0] || ''); + if (!updated.includes(active) || this.isTopicEmpty(active)) { + this.activeChartTopic.set(this.findFirstNonEmptyTopic(updated)); } } @@ -1871,13 +1910,12 @@ export class UniTrendParentComponent implements OnInit { } } - // Topic tab toggle (data reuses instantly) + // Topic tab toggle (data reuses instantly, no router navigation to prevent chart flickering) updateActiveChartTopic(topic: string) { if (this.isTopicEmpty(topic)) { return; } this.activeChartTopic.set(topic); - this.updateUrlParams(); } // Autocomplete query changes for institutions diff --git a/webapp/src/app/resolvers/uni-trend.resolver.ts b/webapp/src/app/resolvers/uni-trend.resolver.ts index b61b49fa..9eef6b9e 100644 --- a/webapp/src/app/resolvers/uni-trend.resolver.ts +++ b/webapp/src/app/resolvers/uni-trend.resolver.ts @@ -1,8 +1,13 @@ import { inject } from '@angular/core'; import { ResolveFn } from '@angular/router'; -import { catchError, of, Observable, map } from 'rxjs'; -import { TrendResponse, UniversityRankingsService } from '../api'; +import { catchError, of, Observable, map, forkJoin } from 'rxjs'; +import { + TrendResponse, + UniversityRankingsService, + PersonsService, +} from '../api'; import { SearchResultsStateService } from '../modules/keywords-search/search-results/search-results-state.service'; +import { CredentialService } from '../shared/services/credential.service'; export interface CompareItem { id: string; @@ -19,6 +24,9 @@ export interface UniTrendResolvedData { countries: CompareItem[]; regions: CompareItem[]; authors: CompareItem[]; + initialActiveTopic?: string; + topSuggestions?: any[]; + recommendedAuthors?: any[]; treemapNode?: string | null; } @@ -28,11 +36,18 @@ export const uniTrendResolver: ResolveFn = ( ): Observable => { const params = route.queryParamMap; const searchState = inject(SearchResultsStateService, { optional: true }); + const credentialService = inject(CredentialService, { optional: true }); const searchType = params.get('search_type') || 'publications'; const fuzzy = params.get('fuzzy') !== 'false'; const treemapNode = params.get('treemapNode'); + // Primary institution from user token / credential service + const primaryInstId = + credentialService?.effectiveInstitutionId() || 'I62318514'; + const primaryInstName = + credentialService?.organizationName() || 'Universität Duisburg-Essen'; + // Extract keywords & topics let keywords = params.getAll('keyword'); if (keywords.length === 0) { @@ -79,9 +94,17 @@ export const uniTrendResolver: ResolveFn = ( const cleanId = parts[0].includes('/') ? parts[0].split('/').pop() || parts[0] : parts[0]; - return { id: cleanId, name: parts[1] || cleanId }; + const isPrimary = + cleanId.toLowerCase() === primaryInstId.toLowerCase() || + primaryInstId.toLowerCase().includes(cleanId.toLowerCase()); + const name = parts[1] || (isPrimary ? primaryInstName : parts[0]); + return { id: cleanId, name }; }); + if (parsedInstitutions.length === 0 && searchType !== 'authors') { + parsedInstitutions.push({ id: primaryInstId, name: primaryInstName }); + } + const countryParams = params.getAll('countries'); const parsedCountries: CompareItem[] = countryParams.map((c) => { const parts = c.split('|'); @@ -103,15 +126,22 @@ export const uniTrendResolver: ResolveFn = ( const instIds = parsedInstitutions.length > 0 ? parsedInstitutions.map((i) => i.id) - : ['I62318514']; + : [primaryInstId]; const countryIds = parsedCountries.length > 0 ? parsedCountries.map((c) => c.id) : ['DE']; const regionIds = parsedRegions.map((r) => r.id); const authorIds = parsedAuthors.map((a) => a.id); const apiService = inject(UniversityRankingsService); + const personsService = inject(PersonsService, { optional: true }); - return apiService + const primaryTopic = topics[0] || 'Artificial Intelligence'; + const countryFilter = + parsedCountries.length > 0 ? parsedCountries[0].id : undefined; + const regionFilter = + parsedRegions.length > 0 ? parsedRegions[0].id : undefined; + + const trendObs$ = apiService .getTrendApiInseServiceUniversityRankingsTrendGet( topics, keywords, @@ -122,9 +152,94 @@ export const uniTrendResolver: ResolveFn = ( authorIds, searchType as any, ) - .pipe( - catchError(() => of(null)), - map((trendResponse) => ({ + .pipe(catchError(() => of(null))); + + const topInstObs$ = + searchType !== 'authors' + ? apiService + .getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet( + primaryTopic, + regionFilter, + countryFilter, + 6, + ) + .pipe(catchError(() => of([]))) + : of([]); + + const recAuthorsObs$ = + searchType === 'authors' && personsService + ? personsService + .searchPersonsList( + undefined, + primaryInstId, + 'cited_by_count', + 'desc', + [primaryTopic], + 1, + 6, + undefined, + ) + .pipe( + map((res: any) => res.results || []), + catchError(() => of([])), + ) + : of([]); + + return forkJoin({ + trendResponse: trendObs$, + topSuggestions: topInstObs$, + recommendedAuthors: recAuthorsObs$, + }).pipe( + map(({ trendResponse, topSuggestions, recommendedAuthors }) => { + // Find the first topic with non-zero publication data + let initialActiveTopic = primaryTopic; + if ( + trendResponse?.series && + trendResponse.series.length > 0 && + topics.length > 0 + ) { + const nonEmptyTopic = topics.find((t) => + trendResponse.series.some((s) => { + if (!s.topic_data) return false; + const tLower = t.toLowerCase().trim(); + const matchingKey = Object.keys(s.topic_data).find((key) => { + const kLower = key.toLowerCase().trim(); + return ( + kLower === tLower || + (kLower.startsWith('news_topic_') && + kLower.slice('news_topic_'.length) === tLower) + ); + }); + if (!matchingKey) return false; + const yearlyList = s.topic_data[matchingKey]; + if (!yearlyList || !Array.isArray(yearlyList)) return false; + const total = yearlyList.reduce( + (sum, item) => sum + (item.raw || 0), + 0, + ); + return total > 0; + }), + ); + if (nonEmptyTopic) { + initialActiveTopic = nonEmptyTopic; + } + } + + // If in author mode and no explicit authors were passed in URL, populate default top authors + if ( + searchType === 'authors' && + parsedAuthors.length === 0 && + recommendedAuthors?.length + ) { + recommendedAuthors.slice(0, 3).forEach((author: any) => { + parsedAuthors.push({ + id: author.id, + name: author.display_name || 'Unbekannt', + }); + }); + } + + return { trendResponse, searchType, topics, @@ -134,7 +249,11 @@ export const uniTrendResolver: ResolveFn = ( countries: parsedCountries, regions: parsedRegions, authors: parsedAuthors, + initialActiveTopic, + topSuggestions: topSuggestions as any[], + recommendedAuthors: recommendedAuthors as any[], treemapNode, - })), - ); + }; + }), + ); }; From d4a4bfa2c7aaf03cb58e1492efe13a8fc5670a48 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Sat, 25 Jul 2026 23:26:08 +0200 Subject: [PATCH 10/15] added optional parameters to topic chip to get the correct hue for hsl conversion (required by ECharts). Changed components to adapt the new color --- .../uni-pie-chart/uni-pie-chart.component.ts | 57 ++++++++++++----- .../uni-trend-chart.component.ts | 19 ++++-- .../uni-trend-parent.component.ts | 64 +++++++++++++++---- .../src/app/resolvers/utils/topic-colors.ts | 14 +++- .../topic-treemap/topic-treemap.component.ts | 13 ++-- 5 files changed, 123 insertions(+), 44 deletions(-) diff --git a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts index 14406c41..1454888b 100644 --- a/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-pie-chart/uni-pie-chart.component.ts @@ -8,7 +8,10 @@ import { CommonModule } from '@angular/common'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; import { TrendResponse } from '../../../api'; -import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { + topicHierarchyColor, + TopicColorVariant, +} from '../../../resolvers/utils/topic-colors'; import { MatProgressSpinner } from '@angular/material/progress-spinner'; @@ -25,7 +28,8 @@ export class UniPieChartComponent { readonly entityName = input(null); readonly startYear = input(2010); readonly endYear = input(2025); - readonly getTopicColor = input<(topic: string) => string>(); + readonly getTopicColor = + input<(topic: string, variant?: TopicColorVariant) => string>(); // Inputs for direct rendering (useful for overall top 10 topics chart) readonly titleText = input(null); @@ -33,15 +37,18 @@ export class UniPieChartComponent { readonly loading = input(false); readonly error = input(false); - private resolveTopicColor(topic: string): string { + private resolveTopicColorTokens(topic: string) { if (topic === 'Andere Themen') { - return '#9ca3af'; // gray for "Other" topics + return { color: 'hsl(214, 20%, 93%)', border: 'hsl(214, 20%, 80%)' }; } const customResolver = this.getTopicColor(); - if (customResolver) { - return customResolver(topic); - } - return topicHierarchyColor({ name: topic }); + const bgColor = customResolver + ? customResolver(topic, 'bg') + : topicHierarchyColor({ name: topic }, 'bg'); + const border = customResolver + ? customResolver(topic, 'border') + : topicHierarchyColor({ name: topic }, 'border'); + return { color: bgColor, border }; } readonly chartOptions = computed(() => { @@ -79,13 +86,19 @@ export class UniPieChartComponent { // 3. If direct pieData input is provided, use it const directData = this.pieData(); if (directData !== null) { - pieDataList = directData.map((item) => ({ - value: item.value, - name: item.name, - itemStyle: { - color: this.resolveTopicColor(item.name), - }, - })); + pieDataList = directData.map((item) => { + const tokens = this.resolveTopicColorTokens(item.name); + return { + value: item.value, + name: item.name, + itemStyle: { + color: tokens.color, + opacity: 0.95, + borderColor: tokens.border, + borderWidth: 1.5, + }, + }; + }); title = this.titleText() ?? 'Themenverteilung'; } else { // Otherwise, filter and extract from TrendResponse @@ -125,11 +138,15 @@ export class UniPieChartComponent { const totalRaw = filtered.reduce((sum, item) => sum + item.raw, 0); if (totalRaw > 0) { + const tokens = this.resolveTopicColorTokens(topicName); pieDataList.push({ value: totalRaw, name: topicName, itemStyle: { - color: this.resolveTopicColor(topicName), + color: tokens.color, + opacity: 0.95, + borderColor: tokens.border, + borderWidth: 1.5, }, }); } @@ -199,11 +216,17 @@ export class UniPieChartComponent { smooth: true, }, emphasis: { + scale: true, + scaleSize: 6, + itemStyle: { + shadowBlur: 10, + shadowOffsetX: 0, + shadowColor: 'rgba(0, 0, 0, 0.2)', + }, label: { show: true, fontSize: 10, fontWeight: 'bold', - formatter: '{b}\n{c} ({d}%)', }, }, data: pieDataList, diff --git a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts index 4a0fe311..2fc5b890 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-chart/uni-trend-chart.component.ts @@ -79,9 +79,13 @@ export class UniTrendChartComponent { // Build series: Line in top grid, growth volume bars and S-Curve in bottom grid trendData.series.forEach((entity, entityIdx) => { - const color = getFn + const rawColor = getFn ? getFn(entity.entity_id) : entityColors[entityIdx % entityColors.length]; + const color = rawColor.replace( + /hsl\(\s*([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)%\s+([+-]?\d+(?:\.\d+)?)%\s*\)/gi, + 'hsl($1, $2%, $3%)', + ); if ((entity as any).visible === false) { return; } @@ -97,16 +101,13 @@ export class UniTrendChartComponent { return currentMode === 'normalized' ? yrData.normalized : yrData.raw; }); - const isStacked = currentMode === 'total' || currentMode === 'cumulative'; - series.push({ name: `${entity.entity_name}`, type: 'line', xAxisIndex: 0, yAxisIndex: 0, - stack: isStacked ? 'Total' : undefined, areaStyle: { - opacity: isStacked ? 0.3 : 0.12, + opacity: 0.12, }, data: lineData, smooth: true, @@ -142,7 +143,7 @@ export class UniTrendChartComponent { yAxisIndex: 1, data: bars, itemStyle: { - color: color, // Takes the color of the institution! + color: color, }, markLine: entityIdx === 0 @@ -202,9 +203,13 @@ export class UniTrendChartComponent { res += `
`; trendData.series.forEach((entity: TrendSeries, entityIdx: number) => { - const color = getFn + const rawColor = getFn ? getFn(entity.entity_id) : entityColors[entityIdx % entityColors.length]; + const color = rawColor.replace( + /hsl\(\s*([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)%\s+([+-]?\d+(?:\.\d+)?)%\s*\)/gi, + 'hsl($1, $2%, $3%)', + ); if ((entity as any).visible === false) { return; } diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index 91049ea7..f86fc12b 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -48,7 +48,10 @@ import { } from '../../../api'; import { CredentialService } from '../../../shared/services/credential.service'; import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component'; -import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors'; +import { + topicHierarchyColor, + TopicColorVariant, +} from '../../../resolvers/utils/topic-colors'; import { YearRangeSliderComponent } from '../../../shared/ui/year-range-slider/year-range-slider.component'; import { LocationSelectorComponent } from '../../../shared/ui/location-selector/location-selector.component'; import { InstitutionSelectorComponent } from '../../../shared/ui/institution-selector/institution-selector.component'; @@ -260,36 +263,61 @@ export class UniTrendParentComponent implements OnInit { return topicOrKeyword; } - getTopicColor(topic: string): string { + getTopicColor(topic: string, variant: TopicColorVariant = 'base'): string { const mapped = this.getMappedTopic(topic); const entries = this.state?.selectedKeywordEntries() ?? []; const ext = this.state?.extractedKeywords() ?? []; const man = this.state?.manualKeywords() ?? []; + const topicsList = this.state?.topics() ?? []; const all = [...entries, ...ext, ...man]; const targetLower = topic.toLowerCase().trim(); const mappedLower = mapped.toLowerCase().trim(); + const topicObj = topicsList.find( + (t) => + t.display_name?.toLowerCase().trim() === mappedLower || + t.display_name?.toLowerCase().trim() === targetLower || + t.id?.toLowerCase().trim() === targetLower, + ); + if (topicObj) { + return topicHierarchyColor( + { + name: topicObj.display_name, + field_name: topicObj.field?.display_name, + domain_name: topicObj.domain?.display_name, + field_id: topicObj.field?.id, + domain_id: topicObj.domain?.id, + id: topicObj.id, + }, + variant, + ); + } + const match = all.find( (e) => e.topic_mapping?.topic?.display_name?.toLowerCase().trim() === mappedLower || e.topic_mapping?.topic?.display_name?.toLowerCase().trim() === targetLower || - e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower, + e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower || + e.llm_keyword?.keyword?.toLowerCase().trim() === mappedLower, ); if (match && match.topic_mapping?.topic) { - return topicHierarchyColor({ - name: match.topic_mapping.topic.display_name, - field_name: match.topic_mapping.topic.field?.display_name, - domain_name: match.topic_mapping.topic.domain?.display_name, - field_id: match.topic_mapping.topic.field?.id, - domain_id: match.topic_mapping.topic.domain?.id, - id: match.topic_mapping.topic.id, - }); + return topicHierarchyColor( + { + name: match.topic_mapping.topic.display_name, + field_name: match.topic_mapping.topic.field?.display_name, + domain_name: match.topic_mapping.topic.domain?.display_name, + field_id: match.topic_mapping.topic.field?.id, + domain_id: match.topic_mapping.topic.domain?.id, + id: match.topic_mapping.topic.id, + }, + variant, + ); } - return topicHierarchyColor({ name: mapped }); + return topicHierarchyColor({ name: mapped }, variant); } readonly boundGetTopicColor = this.getTopicColor.bind(this); @@ -788,8 +816,16 @@ export class UniTrendParentComponent implements OnInit { } }); - // Preserve existing keys as well - Object.assign(newTopicData, s.topic_data); + // Preserve extra keys only if they are not raw URIs + Object.entries(s.topic_data).forEach(([rk, val]) => { + if ( + !rk.startsWith('http://') && + !rk.startsWith('https://') && + !newTopicData[rk] + ) { + newTopicData[rk] = val; + } + }); return { ...s, diff --git a/webapp/src/app/resolvers/utils/topic-colors.ts b/webapp/src/app/resolvers/utils/topic-colors.ts index 4c91c3bf..789ad4f2 100644 --- a/webapp/src/app/resolvers/utils/topic-colors.ts +++ b/webapp/src/app/resolvers/utils/topic-colors.ts @@ -78,10 +78,15 @@ export function classificationSectionColor( return `hsl(${normalizeHue(hue)} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`; } +export type TopicColorVariant = 'base' | 'bg' | 'border'; + export function topicHierarchyColor( topic: TopicHierarchyColorInput | undefined | null, + variant: TopicColorVariant = 'base', ): string { if (!topic) { + if (variant === 'bg') return 'hsl(214, 80%, 95%)'; + if (variant === 'border') return 'hsl(214, 60%, 85%)'; return 'hsl(214 82% 42%)'; } @@ -102,7 +107,14 @@ export function topicHierarchyColor( stableHue(fallbackIdentity); const hue = normalizeHue(baseHue); - return `hsl(${hue} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`; + if (variant === 'bg') { + return `hsl(${hue}, 75%, 80%)`; + } + if (variant === 'border') { + return `hsl(${hue}, 60%, 65%)`; + } + + return `hsl(${hue}, ${FIELD_COLOR_SATURATION}%, ${FIELD_COLOR_LIGHTNESS}%)`; } function normalizeColorKey( diff --git a/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts index 9b31a0b5..28e37196 100644 --- a/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts +++ b/webapp/src/app/shared/ui/topic-treemap/topic-treemap.component.ts @@ -36,7 +36,7 @@ interface TreemapBreadcrumb { styleUrl: './topic-treemap.component.scss', }) export class TopicTreemapComponent implements OnChanges { - private readonly fieldColorOpacity = 0.78; + private readonly fieldColorOpacity = 0.95; @Input() data?: TopicTreemapData; @Input() loading = false; @Input() selectedNodeId?: string; @@ -103,10 +103,13 @@ export class TopicTreemapComponent implements OnChanges { private buildOptions(): EChartsOption { const fields = this.data?.fields ?? []; const hierarchyData = fields.map((field) => { - const fieldColor = topicHierarchyColor({ - field_id: field.id, - field_name: field.name, - }); + const fieldColor = topicHierarchyColor( + { + field_id: field.id, + field_name: field.name, + }, + 'bg', + ); return { id: `field:${field.id}`, From 1810918e433c0551b808ffd67b56bee49538f937 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:22:50 +0200 Subject: [PATCH 11/15] move headers to function --- .../main/inse/integrations/elasticsearch.py | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index afc08614..83532750 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -110,6 +110,10 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]: return None +def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]: + return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type} + + def _wrap_exception(e: Exception) -> Exception: logger.exception(f"Elasticsearch raised an exception: {e}") if isinstance(e, httpx.HTTPStatusError): @@ -177,8 +181,6 @@ async def search( elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} - payload: Dict[str, Any] = {} if body is not None: @@ -221,7 +223,7 @@ async def search( try: response = await client.post( - f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key) ) response.raise_for_status() return response.json() @@ -234,14 +236,13 @@ async def open_point_in_time( ) -> str: """Opens a point-in-time on the given index and returns its id.""" elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.post( f"{elasticsearch_url}/{index}/_pit", params={"keep_alive": keep_alive}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json()["id"] @@ -252,7 +253,6 @@ async def open_point_in_time( async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: @@ -260,7 +260,7 @@ async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: "DELETE", f"{elasticsearch_url}/_pit", json={"id": pit_id}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() except Exception as exc: @@ -281,7 +281,6 @@ async def scan( ``index.max_result_window``, so it can stream result sets larger than 10k. """ elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None @@ -301,7 +300,7 @@ async def scan( try: response = await client.post( - f"{elasticsearch_url}/_search", json=payload, headers=headers + f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key) ) response.raise_for_status() except Exception as exc: @@ -340,7 +339,6 @@ async def get( elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} params = {} if source is not None: @@ -349,7 +347,7 @@ async def get( client = get_client() try: response = await client.get( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers + f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key) ) response.raise_for_status() return response.json() @@ -364,14 +362,13 @@ async def update( cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.post( f"{elasticsearch_url}/{index}/_update/{doc_id}", json={"doc": doc}, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json() @@ -386,14 +383,13 @@ async def index_doc( cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} client = get_client() try: response = await client.put( f"{elasticsearch_url}/{index}/_doc/{doc_id}", json=document, - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() return response.json() @@ -432,7 +428,6 @@ async def count( cluster = clusters.pop() elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"} if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) @@ -443,7 +438,7 @@ async def count( client = get_client() try: response = await client.post( - f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=headers + f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key) ) response.raise_for_status() return response.json().get("count", 0) @@ -474,7 +469,7 @@ async def msearch( cluster = c elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"} + headers = _headers(api_key, content_type="application/x-ndjson") lines = [] for idx, body in searches: @@ -493,7 +488,7 @@ async def msearch( response = await client.post( f"{elasticsearch_url}/_msearch", content=ndjson_payload.encode("utf-8"), - headers=headers, + headers=_headers(api_key), ) response.raise_for_status() res_json = response.json() From b0e4ad639eecf9b57a97405bed31d7cdec0bfe40 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:34:02 +0200 Subject: [PATCH 12/15] centralize HTTP request handling --- .../main/inse/integrations/elasticsearch.py | 186 ++++++++---------- 1 file changed, 77 insertions(+), 109 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 83532750..250786af 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -129,6 +129,51 @@ def _wrap_exception(e: Exception) -> Exception: return ElasticsearchException(f"Unexpected Elasticsearch error: {e}") +async def _request( + method: str, + cluster: ESCluster, + path: str, + *, + json_body: Optional[Any] = None, + params: Optional[Dict[str, Any]] = None, + content: Optional[bytes] = None, + content_type: str = "application/json", +) -> httpx.Response: + """Sends an authenticated request to cluster and returns the raw response. + + Args: + method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE"). + cluster: The Elasticsearch cluster to send the request to. + path: The path appended to the cluster URL (without leading slash). + json_body: Optional JSON-serialisable request body. + params: Optional query parameters. + content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body. + content_type: The Content-Type header value. + + Returns: + httpx.Response: The successful response (status already checked). + """ + + elasticsearch_url, api_key = _cluster_credentials(cluster) + client = get_client() + + try: + response = await client.request( + method, + f"{elasticsearch_url}/{path}", + json=json_body, + params=params, + content=content, + headers=_headers(api_key, content_type=content_type), + ) + + response.raise_for_status() + + return response + except Exception as exc: + raise _wrap_exception(exc) from exc + + async def search( index: ESIndex | List[ESIndex] | str | List[str], query: Optional[Dict] = None, @@ -179,8 +224,6 @@ async def search( elif len(clusters) == 1: cluster = clusters.pop() - elasticsearch_url, api_key = _cluster_credentials(cluster) - payload: Dict[str, Any] = {} if body is not None: @@ -212,59 +255,33 @@ async def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) - client = get_client() logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}" + f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" ) + if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) else: index_str = str(index) - try: - response = await client.post( - f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload) + + return response.json() async def open_point_in_time( index: str, keep_alive: str = "1m", cluster: str = "nes" ) -> str: """Opens a point-in-time on the given index and returns its id.""" - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive}) - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index}/_pit", - params={"keep_alive": keep_alive}, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json()["id"] - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json()["id"] async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None: """Closes a previously opened point-in-time.""" - elasticsearch_url, api_key = _cluster_credentials(cluster) - client = get_client() - try: - response = await client.request( - "DELETE", - f"{elasticsearch_url}/_pit", - json={"id": pit_id}, - headers=_headers(api_key), - ) - response.raise_for_status() - except Exception as exc: - raise _wrap_exception(exc) from exc + await _request("DELETE", cluster, "_pit", json_body={"id": pit_id}) async def scan( @@ -280,12 +297,9 @@ async def scan( Unlike ``from``/``size`` pagination, this is not bounded by ``index.max_result_window``, so it can stream result sets larger than 10k. """ - elasticsearch_url, api_key = _cluster_credentials(cluster) - pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) search_after: Optional[List] = None try: - client = get_client() while True: payload: Dict[str, Any] = { "size": page_size, @@ -298,14 +312,7 @@ async def scan( if search_after is not None: payload["search_after"] = search_after - try: - response = await client.post( - f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - except Exception as exc: - raise _wrap_exception(exc) from exc - + response = await _request("POST", cluster, "_search", json_body=payload) result = response.json() hits = result.get("hits", {}).get("hits", []) @@ -337,22 +344,13 @@ async def get( if isinstance(index, ESIndex): cluster = _index_to_cluster(index) or cluster - elasticsearch_url, api_key = _cluster_credentials(cluster) - - params = {} if source is not None: params["_source_includes"] = ",".join(source) - client = get_client() - try: - response = await client.get( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params) + + return response.json() async def update( @@ -361,19 +359,11 @@ async def update( doc: Dict[str, Any], cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request( + "POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc} + ) - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index}/_update/{doc_id}", - json={"doc": doc}, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json() async def index_doc( @@ -382,19 +372,11 @@ async def index_doc( document: Dict[str, Any], cluster: ESCluster = ESCluster.NES, ) -> Dict[str, Any]: - elasticsearch_url, api_key = _cluster_credentials(cluster) + response = await _request( + "PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document + ) - client = get_client() - try: - response = await client.put( - f"{elasticsearch_url}/{index}/_doc/{doc_id}", - json=document, - headers=_headers(api_key), - ) - response.raise_for_status() - return response.json() - except Exception as exc: - raise _wrap_exception(exc) from exc + return response.json() async def count( @@ -427,23 +409,15 @@ async def count( if len(clusters) == 1: cluster = clusters.pop() - elasticsearch_url, api_key = _cluster_credentials(cluster) - if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) else: index_str = str(index) payload = {"query": query} if query else {} - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key) - ) - response.raise_for_status() - return response.json().get("count", 0) - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload) + + return response.json().get("count", 0) async def msearch( @@ -468,9 +442,6 @@ async def msearch( if c is not None: cluster = c - elasticsearch_url, api_key = _cluster_credentials(cluster) - headers = _headers(api_key, content_type="application/x-ndjson") - lines = [] for idx, body in searches: if isinstance(idx, list): @@ -483,16 +454,13 @@ async def msearch( ndjson_payload = "\n".join(lines) + "\n" - client = get_client() - try: - response = await client.post( - f"{elasticsearch_url}/_msearch", - content=ndjson_payload.encode("utf-8"), - headers=_headers(api_key), - ) - response.raise_for_status() - res_json = response.json() - return res_json.get("responses", []) - except Exception as exc: - raise _wrap_exception(exc) from exc + response = await _request( + "POST", + cluster, + "_msearch", + content=ndjson_payload.encode("utf-8"), + content_type="application/x-ndjson", + ) + + return response.json().get("responses", []) From 28726cf4c7c888572fa10ed115790944d0a83840 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:43:39 +0200 Subject: [PATCH 13/15] add env value to enable logging of outgoing Elasticsearch queries --- service/src/main/inse/.env | 3 +++ service/src/main/inse/integrations/elasticsearch.py | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 36f353cf..152f348d 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -12,6 +12,9 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw== +# Debugging: Log every outgoing Elasticsearch query (index + payload) +PRINT_ES_QUERIES=false + # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 250786af..2f0de418 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -255,9 +255,10 @@ async def search( "At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided" ) - logger.debug( - f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" - ) + if config.settings.print_es_queries: + logger.debug( + f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}" + ) if isinstance(index, list): index_str = ",".join(str(idx) for idx in index) From e57875d2a503c8be6b8ce547434903dfa5728a0f Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 09:48:35 +0200 Subject: [PATCH 14/15] add logging for Elasticsearch request timings --- service/src/main/inse/.env | 2 ++ service/src/main/inse/config.py | 2 ++ service/src/main/inse/integrations/elasticsearch.py | 13 +++++++++++++ 3 files changed, 17 insertions(+) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 152f348d..9fedc0af 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -14,6 +14,8 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false +# Debugging: Log the duration of every Elasticsearch request +PRINT_ES_TIMINGS=false # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index aebc16c6..6075aa8b 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -69,6 +69,8 @@ class Settings(BaseSettings): elasticsearch_api_key: Optional[str] = None elasticsearch_inse_url: Optional[str] = None elasticsearch_inse_api_key: Optional[str] = None + print_es_queries: bool = False + print_es_timings: bool = False model_config = SettingsConfigDict(env_file=str(ENV_FILE)) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 2f0de418..05a81575 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -1,5 +1,6 @@ import json import logging +import time from typing import Any, Dict, AsyncIterator, List, Optional, Tuple import httpx @@ -157,6 +158,7 @@ async def _request( elasticsearch_url, api_key = _cluster_credentials(cluster) client = get_client() + start = time.perf_counter() try: response = await client.request( method, @@ -169,8 +171,19 @@ async def _request( response.raise_for_status() + if config.settings.print_es_timings: + elapsed_ms = (time.perf_counter() - start) * 1000 + logger.debug( + f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms" + ) + return response except Exception as exc: + if config.settings.print_es_timings: + elapsed_ms = (time.perf_counter() - start) * 1000 + logger.debug( + f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms" + ) raise _wrap_exception(exc) from exc From 448922d907cd580ca35bc56f88d143d8dda031db Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sun, 26 Jul 2026 12:58:38 +0200 Subject: [PATCH 15/15] enable logging of Elasticsearch request timings --- service/src/main/inse/.env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/src/main/inse/.env b/service/src/main/inse/.env index 9fedc0af..a49ebae6 100644 --- a/service/src/main/inse/.env +++ b/service/src/main/inse/.env @@ -15,7 +15,7 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM # Debugging: Log every outgoing Elasticsearch query (index + payload) PRINT_ES_QUERIES=false # Debugging: Log the duration of every Elasticsearch request -PRINT_ES_TIMINGS=false +PRINT_ES_TIMINGS=true # Sentence Transformers Configuration SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base