diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py index fbc403c0..b61c2e66 100644 --- a/service/src/main/inse/university_ranking/model.py +++ b/service/src/main/inse/university_ranking/model.py @@ -69,4 +69,11 @@ class AutocompleteLocationItem(BaseModel): id: str display_name: str code: str - type: Literal['country', 'continent'] \ No newline at end of file + type: Literal['country', 'continent'] + +class TopTopicItem(BaseModel): + name: str + count: int + +class TopTopicsResponse(BaseModel): + items: List[TopTopicItem] \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py index c5c7c9e5..0bd2b823 100644 --- a/service/src/main/inse/university_ranking/service.py +++ b/service/src/main/inse/university_ranking/service.py @@ -10,7 +10,8 @@ from .model import ( TrendResponse, TopInstitutionItem, AutocompleteLocationItem, - TrendSearchType + TrendSearchType, + TopTopicsResponse ) from .trend_strategies import TrendStrategy @@ -109,4 +110,24 @@ async def get_top_institutions( async def get_autocomplete_locations( query: str = Query(..., description="Query text to search for countries/continents") ): - return await trend_logic.autocomplete_locations(query) \ No newline at end of file + return await trend_logic.autocomplete_locations(query) + +@router.get( + "/top-topics", + response_model=TopTopicsResponse, + summary="Returns top 10 research topics for a selected entity." +) +async def get_top_topics( + entity_id: str = Query(..., description="Entity ID"), + entity_type: str = Query(..., description="Entity type: institution, author, country, region"), + start_year: int = Query(2010, description="Start year"), + end_year: int = Query(2025, description="End year"), + search_type: str = Query("publications", description="Search strategy type") +): + return await trend_logic.get_top_topics_for_entity( + entity_id=entity_id, + entity_type=entity_type, + start_year=start_year, + end_year=end_year, + search_type=search_type + ) \ No newline at end of file diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py index 8e1365d7..e99df5f7 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -654,3 +654,106 @@ async def get_trend_data( return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) +async def get_top_topics_for_entity( + entity_id: str, + entity_type: str, + start_year: int, + end_year: int, + search_type: str +) -> Dict[str, Any]: + from inse.university_ranking.trend_logic import continent_country_codes + + # 1. Normalize ID and prepare filter clause + if entity_type == "institution": + entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}" + filter_clause = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.id": entity_url}} + } + } + elif entity_type == "author": + entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id.upper()}" + filter_clause = { + "nested": { + "path": "authorships", + "query": {"term": {"authorships.author.id": entity_url}} + } + } + elif entity_type == "country": + filter_clause = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.country_code": entity_id.strip().upper()}} + } + } + elif entity_type == "region": + ccs = continent_country_codes.get(entity_id, []) + if not ccs: + ccs = [entity_id.strip().upper()] + filter_clause = { + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": [c.upper() for c in ccs]}} + } + } + else: + return {"items": []} + + query = { + "bool": { + "filter": [ + filter_clause, + {"range": {"publication_year": {"gte": start_year, "lte": end_year}}} + ] + } + } + + aggs = { + "top_topics": { + "terms": { + "field": "primary_topic.id", + "size": 10 + }, + "aggs": { + "top_topic_hits": { + "top_hits": { + "size": 1, + "_source": ["primary_topic.display_name"] + } + } + } + } + } + + try: + res = await elasticsearch.search( + index="openalex-works*", + body={"query": query, "aggs": aggs}, + size=0, + cluster="nes" + ) + buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) + + items = [] + for b in buckets: + topic_id = b["key"] + doc_count = b["doc_count"] + hits = b["top_topic_hits"]["hits"]["hits"] + topic_name = "Unknown" + if hits: + topic_name = hits[0]["_source"]["primary_topic"]["display_name"] + items.append({"name": topic_name, "count": doc_count}) + + # Calculate "Other" + total_hits = res.get("hits", {}).get("total", {}).get("value", 0) + sum_top_10 = sum(b["count"] for b in items) + other_count = max(0, total_hits - sum_top_10) + 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 topics for entity in ES: %s", e) + return {"items": []} + diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index f7d65825..e4cd6ebf 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -412,17 +412,25 @@ class AuthorsTrendStrategy(TrendStrategy): return TrendResponse(series=[], years=years_range) # Resolve author names from openalex-authors index using document ids + query_authors_clean = [ + a.split("/")[-1].upper() if a.startswith("http") else a.upper() + for a in query_authors + ] resolved_names = {} try: res = await elasticsearch.search( index="openalex-authors", - body={"query": {"ids": {"values": query_authors}}}, - size=len(query_authors), + body={"query": {"ids": {"values": query_authors_clean}}}, + size=len(query_authors_clean), source=["display_name"], cluster="nes" ) for hit in res.get("hits", {}).get("hits", []): - resolved_names[hit["_id"]] = hit["_source"].get("display_name", hit["_id"]) + short_id = hit["_id"] + full_id = f"https://openalex.org/{short_id}" + display_name = hit["_source"].get("display_name", short_id) + resolved_names[short_id] = display_name + resolved_names[full_id] = display_name except Exception as e: logger.warning("Failed to resolve author details from ES: %s", e)