From 71fe4a54e702f3b580a056d5ef9a717423f06044 Mon Sep 17 00:00:00 2001
From: Kazgatari <56477241+Kazgatari@users.noreply.github.com>
Date: Fri, 24 Jul 2026 16:03:54 +0200
Subject: [PATCH 01/10] added aktuell & aktuell_postproc. Refactored string
literals into constants and lists
---
service/src/main/inse/model.py | 4 +
.../inse/university_ranking/trend_logic.py | 2 +-
.../university_ranking/trend_query_builder.py | 89 ++++++++++++++++++-
.../university_ranking/trend_strategies.py | 82 +++--------------
4 files changed, 107 insertions(+), 70 deletions(-)
diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py
index 970ec14f..7c65a8cb 100644
--- a/service/src/main/inse/model.py
+++ b/service/src/main/inse/model.py
@@ -63,6 +63,10 @@ class ESIndex(StrEnum):
PROJECTS_BUND_V1 = "projects_bund_v1"
+ AKTUELLES = "aktuell"
+ AKTUELLES_POSTPROC = "aktuell_postproc"
+
+
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py
index 74467758..7015e4de 100644
--- a/service/src/main/inse/university_ranking/trend_logic.py
+++ b/service/src/main/inse/university_ranking/trend_logic.py
@@ -448,7 +448,7 @@ async def get_top_topics_for_entity(
if search_type == "news":
try:
res = await elasticsearch.search(
- index="aktuell_postproc",
+ index=ESIndex.AKTUELLES_POSTPROC.value,
body={
"query": {"match_all": {}},
"size": 0,
diff --git a/service/src/main/inse/university_ranking/trend_query_builder.py b/service/src/main/inse/university_ranking/trend_query_builder.py
index ce7f0ed3..573c72e7 100644
--- a/service/src/main/inse/university_ranking/trend_query_builder.py
+++ b/service/src/main/inse/university_ranking/trend_query_builder.py
@@ -146,7 +146,7 @@ class TrendMetadataResolver:
return topic_ids
try:
res = await elasticsearch.search(
- index="openalex-topics",
+ index=ESIndex.OPENALEX_TOPICS.value,
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}},
size=len(topic_names) * 2,
source=["id", "display_name"],
@@ -305,3 +305,90 @@ class TrendQueryBuilder:
},
}
}
+
+ @staticmethod
+ def build_bund_keyword_query(keyword: str) -> Dict[str, Any]:
+ """Builds keyword filter clause for BUND projects."""
+ return {
+ "bool": {
+ "should": [{"match": {field: keyword}} for field in BUND_PROJECT_TEXT_FIELDS],
+ "minimum_should_match": 1,
+ }
+ }
+
+ @staticmethod
+ def build_dfg_keyword_query(keyword: str) -> Dict[str, Any]:
+ """Builds keyword filter clause for DFG projects."""
+ return {
+ "bool": {
+ "should": [
+ {"match": {field: keyword}} for field in DFG_PROJECT_TEXT_FIELDS
+ ] + [
+ {"nested": {"path": "publications", "query": {"match": {"publications.title": keyword}}}},
+ {
+ "nested": {
+ "path": "subject_classification",
+ "query": {
+ "bool": {
+ "should": [
+ {"match": {"subject_classification.fach": keyword}},
+ {"match": {"subject_classification.fachkollegium": keyword}},
+ {"match": {"subject_classification.wissenschaftsbereich": keyword}},
+ ],
+ "minimum_should_match": 1,
+ }
+ },
+ }
+ },
+ ],
+ "minimum_should_match": 1,
+ }
+ }
+
+ @staticmethod
+ def build_cordis_keyword_query(keyword: str) -> Dict[str, Any]:
+ """Builds keyword filter clause for EU CORDIS projects."""
+ return {
+ "bool": {
+ "should": [{"match": {field: keyword}} for field in CORDIS_PROJECT_TEXT_FIELDS],
+ "minimum_should_match": 1,
+ }
+ }
+
+ @staticmethod
+ def build_bund_receiver_clause(aliases: List[str]) -> Dict[str, Any]:
+ """Builds Zuwendungsempfänger matching clause for BUND projects."""
+ return {
+ "bool": {
+ "should": [
+ {"match": {BUND_RECEIVER_FIELD: {"query": alias, "operator": "and"}}}
+ for alias in aliases
+ ],
+ "minimum_should_match": 1,
+ }
+ }
+
+
+BUND_RECEIVER_FIELD = "Zuwendungsempfänger"
+BUND_PROJECT_TEXT_FIELDS = [
+ "Thema",
+ "Klartext Leistungsplansystematik",
+ "Förderprofil",
+ "Leistungsplansystematik_fullname",
+]
+
+DFG_PROJECT_TEXT_FIELDS = [
+ "title_de",
+ "title_en",
+ "description",
+ "subject_area_de",
+ "subject_area_en",
+ "abstract_de",
+ "abstract_en",
+ "final_report_abstract_de",
+ "final_report_abstract_en",
+]
+
+CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
+AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
+
diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py
index ca60e79f..be2705ba 100644
--- a/service/src/main/inse/university_ranking/trend_strategies.py
+++ b/service/src/main/inse/university_ranking/trend_strategies.py
@@ -16,6 +16,7 @@ from .model import (
from .trend_query_builder import (
DEFAULT_INSTITUTION_ID,
DEFAULT_INSTITUTION_NAME,
+ AKTUELLES_SEARCH_FIELDS,
TrendMetadataResolver,
TrendQueryBuilder,
clean_inst_id,
@@ -573,8 +574,8 @@ class PatentsTrendStrategy(TrendStrategy):
"aggs": {"by_year": {"terms": {"field": "date_publication_year", "size": 100}}},
}
- msearch_queries.append(("uspto_patents_3.0", uspto_query))
- msearch_queries.append(("epo_index_1.0", epo_query))
+ msearch_queries.append((ESIndex.USPTO_INDEX.value, uspto_query))
+ msearch_queries.append((ESIndex.EPO_INDEX.value, epo_query))
topic_search_indices.append(t)
if msearch_queries:
@@ -806,17 +807,17 @@ class ProjectsTrendStrategy(TrendStrategy):
(
ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
- "projects_cordiseu_heurope_openalex_topics",
+ ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value,
),
(
ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
- "projects_cordiseu_h2020_openalex_topics",
+ ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value,
),
(
ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
ESIndex.CORDIS_EU_FP7_PROJECTS,
- "projects_cordiseu_fp7_openalex_topics",
+ ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value,
),
]
@@ -834,15 +835,10 @@ class ProjectsTrendStrategy(TrendStrategy):
bund_filters = []
if entity_type == "institution":
aliases = resolved_aliases.get(entity_val, [])
- bund_filters.append({
- "bool": {
- "should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
- "minimum_should_match": 1,
- }
- })
+ bund_filters.append(TrendQueryBuilder.build_bund_receiver_clause(aliases))
if fuzzy:
- p_ids = topic_project_ids[topic].get("projects_bund_openalex_topics", [])
+ p_ids = topic_project_ids[topic].get(ESIndex.PROJECTS_BUND_TOPICS.value, [])
if p_ids:
bund_filters.append({"ids": {"values": p_ids}})
bund_query = {"query": {"bool": {"filter": bund_filters}}}
@@ -852,19 +848,7 @@ class ProjectsTrendStrategy(TrendStrategy):
bund_query = {
"query": {
"bool": {
- "filter": [
- {
- "bool": {
- "should": [
- {"match": {"Thema": keyword}},
- {"match": {"Klartext Leistungsplansystematik": keyword}},
- {"match": {"Förderprofil": keyword}},
- {"match": {"Leistungsplansystematik_fullname": keyword}},
- ],
- "minimum_should_match": 1,
- }
- }
- ] + bund_filters
+ "filter": [TrendQueryBuilder.build_bund_keyword_query(keyword)] + bund_filters
}
}
}
@@ -927,39 +911,7 @@ class ProjectsTrendStrategy(TrendStrategy):
else:
if dfg_inst_pids is not None:
dfg_filters.append({"ids": {"values": dfg_inst_pids}})
-
- dfg_filters.append({
- "bool": {
- "should": [
- {"match": {"title_de": keyword}},
- {"match": {"title_en": keyword}},
- {"match": {"description": keyword}},
- {"match": {"subject_area_de": keyword}},
- {"match": {"subject_area_en": keyword}},
- {"match": {"abstract_de": keyword}},
- {"match": {"abstract_en": keyword}},
- {"match": {"final_report_abstract_de": keyword}},
- {"match": {"final_report_abstract_en": keyword}},
- {"nested": {"path": "publications", "query": {"match": {"publications.title": keyword}}}},
- {
- "nested": {
- "path": "subject_classification",
- "query": {
- "bool": {
- "should": [
- {"match": {"subject_classification.fach": keyword}},
- {"match": {"subject_classification.fachkollegium": keyword}},
- {"match": {"subject_classification.wissenschaftsbereich": keyword}},
- ],
- "minimum_should_match": 1,
- }
- },
- }
- },
- ],
- "minimum_should_match": 1,
- }
- })
+ dfg_filters.append(TrendQueryBuilder.build_dfg_keyword_query(keyword))
if include_dfg:
dfg_payload = {
@@ -998,12 +950,7 @@ class ProjectsTrendStrategy(TrendStrategy):
"bool": {
"filter": [
{"terms": {"id": entity_project_ids}},
- {
- "bool": {
- "should": [{"match": {"title": keyword}}, {"match": {"objective": keyword}}],
- "minimum_should_match": 1,
- }
- },
+ TrendQueryBuilder.build_cordis_keyword_query(keyword),
]
}
}
@@ -1139,7 +1086,6 @@ class NewsTrendStrategy(TrendStrategy):
for t in topics
}
- AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
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
@@ -1160,7 +1106,7 @@ class NewsTrendStrategy(TrendStrategy):
news_ids: Set[str] = set()
try:
async for hit in elasticsearch.scan(
- index="aktuell_postproc",
+ index=ESIndex.AKTUELLES_POSTPROC.value,
query=es_query,
source=["news_id"],
cluster=ESCluster.INSE,
@@ -1182,7 +1128,7 @@ class NewsTrendStrategy(TrendStrategy):
}
}
async for hit in elasticsearch.scan(
- index="aktuell",
+ index=ESIndex.AKTUELLES.value,
query=content_query,
source=["news_id"],
cluster=ESCluster.INSE,
@@ -1219,7 +1165,7 @@ class NewsTrendStrategy(TrendStrategy):
"size": 0,
"_source": False,
}
- chunk_queries.append(("aktuell", q_body))
+ chunk_queries.append((ESIndex.AKTUELLES.value, q_body))
if chunk_queries:
try:
--
2.56.1
From b616d061bb02e3d03c1263296ead4bca8d033f2e Mon Sep 17 00:00:00 2001
From: Kazgatari <56477241+Kazgatari@users.noreply.github.com>
Date: Fri, 24 Jul 2026 16:37:32 +0200
Subject: [PATCH 02/10] fixed top 20 projects year slider (forgot to add year
in query)
---
.../test_trend_strategies.py | 14 +++++++
.../inse/university_ranking/trend_logic.py | 39 ++++++++++++-------
2 files changed, 39 insertions(+), 14 deletions(-)
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 e79e02fa..e4c063ef 100644
--- a/service/src/main/inse/university_ranking/test_trend_strategies.py
+++ b/service/src/main/inse/university_ranking/test_trend_strategies.py
@@ -157,6 +157,19 @@ async def test_get_top_topics_for_entity():
assert "items" in res
+@pytest.mark.anyio
+async def test_get_top_topics_for_entity_projects():
+ res = await get_top_topics_for_entity(
+ entity_id="https://openalex.org/I62318514",
+ entity_type="institution",
+ start_year=2018,
+ end_year=2022,
+ search_type="projects",
+ )
+ assert isinstance(res, dict)
+ assert "items" in res
+
+
@pytest.mark.anyio
async def test_get_trend_data_delegation():
res = await get_trend_data(
@@ -165,3 +178,4 @@ async def test_get_trend_data_delegation():
)
assert res is not None
assert len(res.series) > 0
+
diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py
index 7015e4de..caf30bc9 100644
--- a/service/src/main/inse/university_ranking/trend_logic.py
+++ b/service/src/main/inse/university_ranking/trend_logic.py
@@ -296,16 +296,11 @@ async def get_top_topics_for_entity(
project_ids_by_index: Dict[str, List[str]] = {}
- # 1. BUND - use scan to retrieve all project IDs without 10k limits
+ # 1. BUND - filter by institution/country and date range
if include_german:
- bund_filters = []
+ bund_filters = [TrendQueryBuilder.build_date_range_filter("funding_start", start_year, end_year)]
if entity_type == "institution":
- bund_filters.append({
- "bool": {
- "should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
- "minimum_should_match": 1,
- }
- })
+ bund_filters.append(TrendQueryBuilder.build_bund_receiver_clause(aliases))
try:
p_ids = []
async for hit in elasticsearch.scan(
@@ -321,7 +316,7 @@ async def get_top_topics_for_entity(
except Exception as e:
logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e)
- # 2. DFG - scan institutes & projects
+ # 2. DFG - filter by institute projects and date range
if include_german:
try:
dfg_pids = []
@@ -338,7 +333,7 @@ async def get_top_topics_for_entity(
dfg_pids.append(str(p["project_id"]))
if dfg_pids or entity_type != "institution":
- dfg_filters = []
+ dfg_filters = [TrendQueryBuilder.build_date_range_filter("funding_start", start_year, end_year)]
if dfg_pids:
dfg_filters.append({"ids": {"values": dfg_pids}})
@@ -357,7 +352,7 @@ async def get_top_topics_for_entity(
except Exception as e:
logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e)
- # 3. EU CORDIS
+ # 3. EU CORDIS - filter orgs and verify project start dates
eu_indices = [
(ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value),
(ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value),
@@ -380,9 +375,25 @@ async def get_top_topics_for_entity(
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
},
)
- eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
- if eu_pids:
- project_ids_by_index[topic_idx] = eu_pids
+ raw_eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
+ if raw_eu_pids:
+ # Filter project IDs by start date range
+ dated_eu_pids = []
+ proj_date_filter = [
+ {"terms": {"id": raw_eu_pids}},
+ TrendQueryBuilder.build_date_range_filter("startDate", start_year, end_year),
+ ]
+ async for hit in elasticsearch.scan(
+ index=proj_idx.value,
+ query={"bool": {"filter": proj_date_filter}},
+ source=["id"],
+ cluster=ESCluster.INSE,
+ ):
+ pid = hit.get("_source", {}).get("id") or hit.get("_id")
+ if pid:
+ dated_eu_pids.append(str(pid))
+ if dated_eu_pids:
+ project_ids_by_index[topic_idx] = dated_eu_pids
except Exception as e:
logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e)
--
2.56.1
From cbbcaa23253893104470a3b0d34b9fac3637647c Mon Sep 17 00:00:00 2001
From: Kazgatari <56477241+Kazgatari@users.noreply.github.com>
Date: Fri, 24 Jul 2026 16:55:28 +0200
Subject: [PATCH 03/10] rewrite projects to not use existing query that pull to
much data and takes to long when not paginated
---
.../inse/university_ranking/trend_logic.py | 8 +-
.../university_ranking/trend_strategies.py | 164 ++++++++----------
2 files changed, 74 insertions(+), 98 deletions(-)
diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py
index caf30bc9..753fb4a7 100644
--- a/service/src/main/inse/university_ranking/trend_logic.py
+++ b/service/src/main/inse/university_ranking/trend_logic.py
@@ -256,9 +256,6 @@ async def get_top_topics_for_entity(
if search_type == "projects":
try:
- from inse.patents.search_client import PatentSearchClient
- patent_client = PatentSearchClient()
-
short_id = clean_inst_id(entity_id)
full_id = to_full_inst_url(entity_id)
@@ -366,14 +363,15 @@ async def get_top_topics_for_entity(
elif entity_type == "country":
filter_clauses.append({"term": {"country": entity_id.strip().upper()}})
- eu_org_res = await patent_client._search(
+ eu_org_res = await elasticsearch.search(
index=org_idx.value,
- payload={
+ body={
"query": {"bool": {"filter": filter_clauses}},
"size": 0,
"_source": False,
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
},
+ cluster=ESCluster.INSE,
)
raw_eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
if raw_eu_pids:
diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py
index be2705ba..d313d49b 100644
--- a/service/src/main/inse/university_ranking/trend_strategies.py
+++ b/service/src/main/inse/university_ranking/trend_strategies.py
@@ -694,9 +694,6 @@ class ProjectsTrendStrategy(TrendStrategy):
if not filters_map:
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
- from inse.patents.search_client import PatentSearchClient
- patent_client = PatentSearchClient()
-
# Resolve DFG project IDs for institutions via scan/search without size limit cutoffs
dfg_institution_projects: Dict[str, List[str]] = {}
@@ -776,33 +773,11 @@ class ProjectsTrendStrategy(TrendStrategy):
for key in filters_map
}
- async def query_project_trends(entity_key: str, entity_type: str, entity_val: Any, topic: str, keyword: str):
- async def get_eu_entity_project_ids(org_index: ESIndex) -> List[str]:
- filter_clauses = []
- if entity_type == "institution":
- aliases = resolved_aliases.get(entity_val, [])
- filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}})
- elif entity_type == "country":
- filter_clauses.append({"term": {"country": entity_val}})
- elif entity_type == "region":
- filter_clauses.append({"terms": {"country": entity_val}})
-
- try:
- res = await patent_client._search(
- index=org_index.value,
- payload={
- "query": {"bool": {"filter": filter_clauses}},
- "size": 0,
- "_source": False,
- "aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
- },
- )
- buckets = res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
- return [b["key"] for b in buckets]
- except Exception as e:
- logger.warning("Failed to query CORDIS orgs index %s: %s", org_index.value, e)
- return []
+ # Batch all project queries into single msearch request
+ msearch_queries = []
+ meta_indices: List[Tuple[str, str, str]] = [] # (entity_key, topic, agg_type)
+ async def prepare_project_trend_queries(entity_key: str, entity_type: str, entity_val: Any, topic: str, keyword: str):
eu_indices = [
(
ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
@@ -821,8 +796,34 @@ class ProjectsTrendStrategy(TrendStrategy):
),
]
+ async def get_eu_entity_project_ids(org_index: ESIndex) -> List[str]:
+ filter_clauses = []
+ if entity_type == "institution":
+ aliases = resolved_aliases.get(entity_val, [])
+ filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}})
+ elif entity_type == "country":
+ filter_clauses.append({"term": {"country": entity_val}})
+ elif entity_type == "region":
+ filter_clauses.append({"terms": {"country": entity_val}})
+
+ try:
+ res = await elasticsearch.search(
+ index=org_index.value,
+ body={
+ "query": {"bool": {"filter": filter_clauses}},
+ "size": 0,
+ "_source": False,
+ "aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
+ },
+ cluster=ESCluster.INSE,
+ )
+ buckets = res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
+ return [b["key"] for b in buckets]
+ except Exception as e:
+ logger.warning("Failed to query CORDIS orgs index %s: %s", org_index.value, e)
+ return []
+
eu_org_ids_list = await asyncio.gather(*(get_eu_entity_project_ids(org_idx) for org_idx, _, _ in eu_indices))
- actual_tasks = []
# BUND
include_bund = True
@@ -868,16 +869,8 @@ class ProjectsTrendStrategy(TrendStrategy):
}
},
}
-
- async def process_bund():
- try:
- res = await patent_client._search(index=ESIndex.PROJECTS_BUND_V1.value, payload=bund_payload)
- return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
- except Exception as e:
- logger.warning("Failed to query BUND projects: %s", e)
- return "date", []
-
- actual_tasks.append(process_bund())
+ msearch_queries.append((ESIndex.PROJECTS_BUND_V1.value, bund_payload))
+ meta_indices.append((entity_key, topic, "date"))
# DFG
include_dfg = True
@@ -920,18 +913,10 @@ class ProjectsTrendStrategy(TrendStrategy):
"_source": False,
"aggs": {"projects_by_year": {"terms": {"field": "funding_start", "size": 100}}},
}
+ msearch_queries.append((ESIndex.DFG_PROJECTS.value, dfg_payload))
+ meta_indices.append((entity_key, topic, "terms"))
- async def process_dfg():
- try:
- res = await patent_client._search(index=ESIndex.DFG_PROJECTS.value, payload=dfg_payload)
- return "terms", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
- except Exception as e:
- logger.warning("Failed to query DFG projects: %s", e)
- return "terms", []
-
- actual_tasks.append(process_dfg())
-
- # EU Cordis
+ # EU CORDIS
for eu_idx, (org_index, proj_index, mapping_key) in enumerate(eu_indices):
entity_project_ids = eu_org_ids_list[eu_idx]
if not entity_project_ids:
@@ -971,53 +956,46 @@ class ProjectsTrendStrategy(TrendStrategy):
}
},
}
+ msearch_queries.append((proj_index.value, proj_payload))
+ meta_indices.append((entity_key, topic, "date"))
- async def process_cordis(p_idx=proj_index, payload=proj_payload):
- try:
- res = await patent_client._search(index=p_idx.value, payload=payload)
- return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
- except Exception as e:
- logger.warning("Failed to query CORDIS projects index %s: %s", p_idx.value, e)
- return "date", []
-
- actual_tasks.append(process_cordis())
-
- if not actual_tasks:
- return
-
- results = await asyncio.gather(*actual_tasks)
- year_counts: Dict[int, int] = {}
- for agg_type, buckets in results:
- for b in buckets:
- if agg_type == "date":
- yr_str = b.get("key_as_string") or str(b.get("key", ""))
- if yr_str:
- try:
- yr = int(yr_str[:4])
- if start_year <= yr <= end_year:
- year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
- except ValueError:
- pass
- else:
- yr_val = b.get("key")
- if yr_val is not None:
- try:
- yr = int(str(yr_val)[:4])
- if start_year <= yr <= end_year:
- year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
- except ValueError:
- pass
-
- for yr, count in year_counts.items():
- accumulated_data[entity_key][topic][yr] = (count, 1)
-
- tasks = []
+ prep_tasks = []
for entity_key, (entity_type, entity_val) in filters_map.items():
for idx, topic in enumerate(topics):
keyword = keywords[idx] if (keywords and idx < len(keywords)) else topic
- tasks.append(query_project_trends(entity_key, entity_type, entity_val, topic, keyword))
+ prep_tasks.append(prepare_project_trend_queries(entity_key, entity_type, entity_val, topic, keyword))
- await asyncio.gather(*tasks)
+ await asyncio.gather(*prep_tasks)
+
+ if msearch_queries:
+ try:
+ responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE)
+ for idx, res in enumerate(responses):
+ entity_key, topic, agg_type = meta_indices[idx]
+ buckets = res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
+ for b in buckets:
+ if agg_type == "date":
+ yr_str = b.get("key_as_string") or str(b.get("key", ""))
+ if yr_str:
+ try:
+ yr = int(yr_str[:4])
+ if start_year <= yr <= end_year:
+ c_cnt, _ = accumulated_data[entity_key][topic][yr]
+ accumulated_data[entity_key][topic][yr] = (c_cnt + b.get("doc_count", 0), 1)
+ except ValueError:
+ pass
+ else:
+ yr_val = b.get("key")
+ if yr_val is not None:
+ try:
+ yr = int(str(yr_val)[:4])
+ if start_year <= yr <= end_year:
+ c_cnt, _ = accumulated_data[entity_key][topic][yr]
+ accumulated_data[entity_key][topic][yr] = (c_cnt + b.get("doc_count", 0), 1)
+ except ValueError:
+ pass
+ except Exception as e:
+ logger.error("Failed to execute msearch for project trends: %s", e)
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
--
2.56.1
From 11ac6525c19289666e5485126ff666f33479a8b4 Mon Sep 17 00:00:00 2001
From: Kazgatari <56477241+Kazgatari@users.noreply.github.com>
Date: Sat, 25 Jul 2026 00:27:54 +0200
Subject: [PATCH 04/10] moved row with filters up above all visuals.
Implemented treemap for fuzzy search. adapted resolver
---
.../uni-trend-parent.component.html | 202 ++++++-----
.../uni-trend-parent.component.ts | 334 ++++++++++++++++--
.../src/app/resolvers/uni-trend.resolver.ts | 73 ++--
3 files changed, 463 insertions(+), 146 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 ccc758ea..eba4f3a6 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
@@ -92,6 +92,87 @@
+
+
+
+ @if (activeConfig().showLocationSelector) {
+
+
+ }
+
+
+ @if (activeConfig().showAuthorSelector) {
+
+
+ }
+
+
+ @if (activeConfig().showInstitutionSelector) {
+
+
+ }
+
+
+ @if (activeConfig().showAuthorSelector) {
+
+
+ }
+
+
@if (isPageResolving() || (isTrendLoading() && !rawTrendResponse())) {
@@ -109,11 +190,11 @@
@if (selectedSearchType() === 'news') {
+ (chipClick)="toggleVisibility('news_topic_' + topic)">
} @else if (selectedTrendTopics().length > 1) {
}
-
-
-
- @if (activeConfig().showLocationSelector) {
-
-
- }
-
-
- @if (activeConfig().showAuthorSelector) {
-
-
- }
-
-
- @if (activeConfig().showInstitutionSelector) {
-
-
- }
-
-
- @if (activeConfig().showAuthorSelector) {
-
-
- }
-
+
+ @if (isFuzzy() && activeTreemapData()) {
+
+
+
+ account_tree
+ Themen-Hierarchie & Verteilung (Treemap)
+ @if (selectedPieEntity()?.name || primaryInstitutionName()) {
+
+ ·
+ {{ selectedPieEntity()?.name || primaryInstitutionName() }}
+
+ }
+
+
+
+
+
+ }
} @else {
trending_up
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 9fd2a328..eb689866 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
@@ -56,6 +56,16 @@ import { AuthorSelectorComponent } from '../../../shared/ui/author-selector/auth
import { AuthorInstitutionSelectorComponent } from '../../../shared/ui/author-institution-selector/author-institution-selector.component';
import { SearchResultsStateService } from '../../keywords-search/search-results/search-results-state.service';
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
+import { TopicTreemapComponent } from '../../../shared/ui/topic-treemap/topic-treemap.component';
+import {
+ TopicTreemapData,
+ TopicTreemapField,
+ TopicTreemapSubfield,
+ TopicTreemapTopic,
+ TopicTreemapValue,
+ TopicTreemapTopicSelect,
+} from '../../../shared/ui/topic-treemap/topic-treemap.models';
+import { TopicsService } from '../../../api/api/topics.service';
export interface CompareItem {
id: string;
@@ -136,6 +146,7 @@ export const TREND_CONFIGS: Record
= {
AuthorSelectorComponent,
AuthorInstitutionSelectorComponent,
LoadingComponent,
+ TopicTreemapComponent,
],
templateUrl: './uni-trend-parent.component.html',
styleUrl: './uni-trend-parent.component.scss',
@@ -143,6 +154,7 @@ export const TREND_CONFIGS: Record = {
})
export class UniTrendParentComponent implements OnInit {
private readonly apiService = inject(UniversityRankingsService);
+ private readonly topicsService = inject(TopicsService);
private readonly institutionsApiService = inject(InstitutionsService);
private readonly personsApiService = inject(PersonsService);
private readonly organizationService = inject(OrganizationService, {
@@ -230,6 +242,12 @@ export class UniTrendParentComponent implements OnInit {
readonly isTopTopicsLoading = signal(false);
readonly topTopicsError = signal(false);
+ // Topic Treemap signals
+ readonly isFuzzy = computed(() => this.state?.fuzzySearch() ?? true);
+ readonly topicTreemap = signal(null);
+ readonly isTreemapLoading = signal(false);
+ readonly selectedTopicTreemapNode = signal(undefined);
+
getMappedTopic(topicOrKeyword: string): string {
const kws = this.keywords();
const topics = this.state?.topicsList() ?? kws;
@@ -299,6 +317,197 @@ export class UniTrendParentComponent implements OnInit {
});
});
+ cleanEntityId(id: string | null | undefined): string {
+ if (!id) return '';
+ const lower = id.toLowerCase().trim();
+ return lower.includes('/') ? lower.split('/').pop()! : lower;
+ }
+
+ // Dynamic Treemap Data for Selected Entity (Institution or Author or Region/Country)
+ readonly activeTreemapData = computed(() => {
+ const data = this.trendResponse();
+ const searchType = this.selectedSearchType();
+ const isFuzzy = this.isFuzzy();
+ if (!data || !data.series || !isFuzzy) return null;
+
+ const startYr = this.startYear();
+ const endYr = this.endYear();
+
+ const activePie = this.selectedPieEntity();
+ let targetEntityId: string | undefined = activePie?.id || undefined;
+ let targetEntityName = activePie?.name || 'Ausgewählte Entität';
+
+ if (!targetEntityId) {
+ if (searchType === 'authors') {
+ const firstAuthor = this.comparisonAuthors()[0];
+ targetEntityId = firstAuthor?.id || undefined;
+ targetEntityName = firstAuthor?.name || 'Autor';
+ } else {
+ targetEntityId = this.primaryInstitution() || undefined;
+ targetEntityName = this.primaryInstitutionName();
+ }
+ }
+
+ const cleanTargetId = targetEntityId
+ ? this.cleanEntityId(targetEntityId)
+ : '';
+
+ let matchingSeries: TrendSeries[] = [];
+ if (searchType === 'news') {
+ matchingSeries = data.series;
+ } else {
+ matchingSeries = data.series.filter(
+ (s) => this.cleanEntityId(s.entity_id) === cleanTargetId,
+ );
+ if (matchingSeries.length === 0 && data.series.length > 0) {
+ matchingSeries = data.series;
+ }
+ }
+
+ if (matchingSeries.length === 0) return null;
+
+ const keywordEntries = this.state?.selectedKeywordEntries() ?? [];
+ const fieldsMap = new Map<
+ string,
+ {
+ id: string;
+ name: string;
+ subfieldsMap: Map<
+ string,
+ {
+ id: string;
+ name: string;
+ topicsMap: Map<
+ string,
+ {
+ id: string;
+ name: string;
+ total: number;
+ values: TopicTreemapValue[];
+ }
+ >;
+ }
+ >;
+ }
+ >();
+
+ matchingSeries.forEach((s) => {
+ Object.entries(s.topic_data || {}).forEach(
+ ([topicName, yearlyDataList]) => {
+ const totalCount = yearlyDataList
+ .filter((y) => y.year >= startYr && y.year <= endYr)
+ .reduce((sum, item) => sum + (item.raw || 0), 0);
+
+ if (totalCount <= 0) return;
+
+ const mappedName = this.getMappedTopic(topicName);
+ const targetLower = topicName.toLowerCase().trim();
+ const mappedLower = mappedName.toLowerCase().trim();
+
+ const match = keywordEntries.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,
+ );
+
+ const fieldName =
+ match?.topic_mapping?.topic?.field?.display_name ||
+ 'Information & Communication Technology';
+ const fieldId = match?.topic_mapping?.topic?.field?.id
+ ? String(match.topic_mapping.topic.field.id)
+ : 'field_ict';
+
+ const subfieldName =
+ match?.topic_mapping?.topic?.subfield?.display_name || fieldName;
+ const subfieldId = match?.topic_mapping?.topic?.subfield?.id
+ ? String(match.topic_mapping.topic.subfield.id)
+ : `subfield_${fieldId}`;
+
+ const topicId = match?.topic_mapping?.topic?.id
+ ? String(match.topic_mapping.topic.id)
+ : topicName;
+
+ if (!fieldsMap.has(fieldId)) {
+ fieldsMap.set(fieldId, {
+ id: fieldId,
+ name: fieldName,
+ subfieldsMap: new Map(),
+ });
+ }
+ const fieldEntry = fieldsMap.get(fieldId)!;
+
+ if (!fieldEntry.subfieldsMap.has(subfieldId)) {
+ fieldEntry.subfieldsMap.set(subfieldId, {
+ id: subfieldId,
+ name: subfieldName,
+ topicsMap: new Map(),
+ });
+ }
+ const subfieldEntry = fieldEntry.subfieldsMap.get(subfieldId)!;
+
+ if (!subfieldEntry.topicsMap.has(topicId)) {
+ const yearlyValues: TopicTreemapValue[] = yearlyDataList
+ .filter((y) => y.year >= startYr && y.year <= endYr)
+ .map((y) => ({
+ year: y.year,
+ count: y.raw || 0,
+ share: y.normalized || 0,
+ }));
+
+ subfieldEntry.topicsMap.set(topicId, {
+ id: topicId,
+ name: topicName,
+ total: totalCount,
+ values: yearlyValues,
+ });
+ }
+ },
+ );
+ });
+
+ const years = Array.from(
+ { length: endYr - startYr + 1 },
+ (_, i) => startYr + i,
+ );
+ const fields: TopicTreemapField[] = Array.from(fieldsMap.values()).map(
+ (f) => {
+ const subfields: TopicTreemapSubfield[] = Array.from(
+ f.subfieldsMap.values(),
+ ).map((sf) => {
+ const topics: TopicTreemapTopic[] = Array.from(sf.topicsMap.values());
+ const sfTotal = topics.reduce((sum, t) => sum + t.total, 0);
+ return {
+ id: sf.id,
+ name: sf.name,
+ total: sfTotal,
+ values: [],
+ topics,
+ };
+ });
+ const fTotal = subfields.reduce((sum, sf) => sum + sf.total, 0);
+ return {
+ id: f.id,
+ name: f.name,
+ total: fTotal,
+ values: [],
+ subfields,
+ };
+ },
+ );
+
+ if (fields.length === 0) return null;
+
+ return {
+ institution_id: cleanTargetId,
+ organization_name: targetEntityName,
+ years,
+ fields,
+ };
+ });
+
// Autocomplete UI state
readonly searchQuery = signal('');
readonly searchResults = signal([]);
@@ -316,6 +525,26 @@ export class UniTrendParentComponent implements OnInit {
readonly entityVisibilityMap = signal
diff --git a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss
index 8a4ca439..041d4755 100644
--- a/webapp/src/app/shared/ui/location-selector/location-selector.component.scss
+++ b/webapp/src/app/shared/ui/location-selector/location-selector.component.scss
@@ -1,21 +1,25 @@
:host {
display: block;
width: 100%;
+ height: 100%;
min-width: 0;
max-width: 100%;
}
.control-card {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
background: white;
- border-radius: 10px;
+ border-radius: 12px;
padding: 1.25rem;
- border: 1px solid #e5e7eb;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
+ border: 1px solid #e2e8f0;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
box-sizing: border-box;
h3 {
font-size: 0.8rem;
- font-weight: 600;
+ font-weight: 700;
text-transform: uppercase;
color: #6b7280;
margin: 0 0 0.75rem 0;
@@ -23,88 +27,10 @@
}
}
-.comparison-list {
- display: flex;
- flex-direction: column;
- gap: 0.4rem;
- max-height: 200px;
- overflow-y: auto;
- margin-bottom: 0.75rem;
-
- .empty-list-info {
- font-size: 0.75rem;
- color: #9ca3af;
- text-align: center;
- padding: 8px 0;
- border: 1px dashed #e5e7eb;
- border-radius: 5px;
- }
-}
-
-.comparison-item {
- display: flex;
- justify-content: space-between;
- align-items: center;
- border: 1px solid #e5e7eb;
- border-radius: 5px;
- padding: 0.3rem 0.5rem;
- transition: all 0.2s ease;
-
- .item-name {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: 0.75rem;
- font-weight: 600;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- max-width: 170px;
-
- mat-icon {
- font-size: 14px;
- width: 14px;
- height: 14px;
- }
- }
-
- .item-actions {
- display: flex;
- align-items: center;
- gap: 4px;
- }
-
- .action-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 2px;
- border-radius: 3px;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- transition: all 0.15s ease;
-
- mat-icon {
- font-size: 14px;
- width: 14px;
- height: 14px;
- }
-
- &:hover {
- background: rgba(0, 0, 0, 0.05);
- }
-
- &.remove-btn:hover {
- color: #ef4444 !important;
- background: #fee2e2;
- }
- }
-}
-
.autocomplete-search {
position: relative;
width: 100%;
+ margin-bottom: 0.75rem;
.search-form-field {
width: 100%;
@@ -113,18 +39,39 @@
input {
width: 100%;
- padding: 0.5rem;
- border-radius: 5px;
+ padding: 0.5rem 0.5rem 0.5rem 0.75rem;
+ border-radius: 6px;
border: 1px solid #d1d5db;
font-size: 0.8125rem;
outline: none;
box-sizing: border-box;
+ line-height: normal;
&:focus {
border-color: #3b82f6;
}
}
}
+.comparison-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+ max-height: 104px;
+ overflow-y: auto;
+ padding-right: 4px;
+ flex: 1;
+ box-sizing: border-box;
+
+ .empty-list-info {
+ font-size: 0.75rem;
+ color: #9ca3af;
+ text-align: center;
+ padding: 12px 8px;
+ border: 1px dashed #e5e7eb;
+ border-radius: 6px;
+ }
+}
+
.autocomplete-results {
position: absolute;
top: 100%;
--
2.56.1
From 2fc972291475905143d92c47bd19404d9c04dfb1 Mon Sep 17 00:00:00 2001
From: Kazgatari <56477241+Kazgatari@users.noreply.github.com>
Date: Sat, 25 Jul 2026 14:51:58 +0200
Subject: [PATCH 06/10] changed color for All view, adapted layout to use same
distance between all components
---
.../uni-trend-parent.component.html | 2 +-
.../uni-trend-parent.component.scss | 14 ++++-------
.../uni-trend-parent.component.ts | 23 +++++++++++++++++++
3 files changed, 29 insertions(+), 10 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 eba4f3a6..5766c149 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
@@ -266,7 +266,7 @@
@if (isFuzzy() && activeTreemapData()) {
-
+
-
- search
+
Einrichtung suchen
+ search
@if (searchQuery()) {