diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 4193f55b..1e34ea34 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -180,11 +180,15 @@ async def search( if body is not None: payload = body + if payload.get("size") == 0 and "_source" not in payload: + payload["_source"] = False else: if query is not None: payload["query"] = query if source is not None: payload["_source"] = source + elif size == 0: + payload["_source"] = False if size is not None: payload["size"] = size if offset is not None: @@ -287,9 +291,8 @@ async def scan( "pit": {"id": pit_id, "keep_alive": keep_alive}, "sort": [{"_shard_doc": "asc"}], "track_total_hits": False, + "_source": source if source is not None else False, } - if source is not None: - payload["_source"] = source if search_after is not None: payload["search_after"] = search_after @@ -393,3 +396,105 @@ async def index_doc( return response.json() except Exception as exc: raise _wrap_exception(exc) from exc + + +async def count( + index: ESIndex | List[ESIndex] | str | List[str], + query: Optional[Dict[str, Any]] = None, + cluster: ESCluster = ESCluster.NES, +) -> int: + """Performs a count request (_count) on the specified Elasticsearch index. + + Args: + index: The index or list of indices to count. + query: Optional query body to filter documents. + cluster: The Elasticsearch cluster to query. + + Returns: + int: The number of matching documents. + """ + clusters = set() + if isinstance(index, list): + for idx in index: + if isinstance(idx, ESIndex): + c = _index_to_cluster(idx) + if c is not None: + clusters.add(c) + elif isinstance(index, ESIndex): + c = _index_to_cluster(index) + if c is not None: + clusters.add(c) + + if len(clusters) == 1: + 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) + 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 + ) + response.raise_for_status() + return response.json().get("count", 0) + except Exception as exc: + raise _wrap_exception(exc) from exc + + +async def msearch( + searches: List[Tuple[ESIndex | str | List[str], Dict[str, Any]]], + cluster: ESCluster = ESCluster.NES, +) -> List[Dict[str, Any]]: + """Performs a multi-search request (_msearch) on Elasticsearch. + + Args: + searches: A list of tuples, each containing (index, payload_dict). + cluster: The Elasticsearch cluster to execute searches on. + + Returns: + List[Dict[str, Any]]: List of response dictionaries for each search in order. + """ + if not searches: + return [] + + first_idx = searches[0][0] + if isinstance(first_idx, ESIndex): + c = _index_to_cluster(first_idx) + if c is not None: + cluster = c + + elasticsearch_url, api_key = _cluster_credentials(cluster) + headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"} + + lines = [] + for idx, body in searches: + if isinstance(idx, list): + idx_str = ",".join(str(i) for i in idx) + else: + idx_str = str(idx) + header_obj = {"index": idx_str} + lines.append(json.dumps(header_obj)) + lines.append(json.dumps(body)) + + 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, + ) + response.raise_for_status() + res_json = response.json() + return res_json.get("responses", []) + except Exception as exc: + raise _wrap_exception(exc) from exc + 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 936c17b4..e79e02fa 100644 --- a/service/src/main/inse/university_ranking/test_trend_strategies.py +++ b/service/src/main/inse/university_ranking/test_trend_strategies.py @@ -1,5 +1,61 @@ import pytest -from inse.university_ranking.trend_strategies import PatentsTrendStrategy, ProjectsTrendStrategy +from inse.university_ranking.trend_strategies import ( + PublicationsTrendStrategy, + AuthorsTrendStrategy, + PatentsTrendStrategy, + ProjectsTrendStrategy, + NewsTrendStrategy, + AllTrendStrategy, +) +from inse.university_ranking.trend_query_builder import ( + TrendQueryBuilder, + TrendMetadataResolver, + clean_inst_id, + to_full_inst_url, +) +from inse.university_ranking.trend_logic import ( + autocomplete_locations, + get_top_institutions_by_region, + get_top_topics_for_entity, + get_trend_data, +) + + +def test_clean_and_to_full_inst_url(): + assert clean_inst_id("https://openalex.org/I62318514") == "I62318514" + assert clean_inst_id("I62318514") == "I62318514" + assert to_full_inst_url("I62318514") == "https://openalex.org/I62318514" + assert to_full_inst_url("https://openalex.org/I62318514") == "https://openalex.org/I62318514" + + +def test_trend_query_builder_clauses(): + topic_clause = TrendQueryBuilder.build_topic_clause("Artificial Intelligence", "T1001", fuzzy=True) + assert "bool" in topic_clause + assert "should" in topic_clause["bool"] + + date_filter = TrendQueryBuilder.build_date_range_filter("publication_year", 2015, 2024) + assert date_filter["range"]["publication_year"]["gte"] == 2015 + assert date_filter["range"]["publication_year"]["lte"] == 2024 + + entity_filter = TrendQueryBuilder.build_entity_nested_filter( + inst_ids=["https://openalex.org/I62318514"], + country_codes=["DE"], + ) + assert "bool" in entity_filter or "nested" in entity_filter + + +@pytest.mark.anyio +async def test_publications_trend_strategy(): + strategy = PublicationsTrendStrategy() + res = await strategy.get_trend( + topics=["Artificial Intelligence"], + fuzzy=True, + institutions=["https://openalex.org/I62318514"], + ) + assert res is not None + assert len(res.series) > 0 + assert "Artificial Intelligence" in res.series[0].topic_data + @pytest.mark.anyio async def test_patents_trend_strategy(): @@ -7,7 +63,7 @@ async def test_patents_trend_strategy(): res = await strategy.get_trend( topics=["Biotechnology and Related Fields"], fuzzy=True, - institutions=["https://openalex.org/I62318514"] + institutions=["https://openalex.org/I62318514"], ) assert res is not None assert len(res.series) > 0 @@ -15,16 +71,97 @@ async def test_patents_trend_strategy(): assert len(series_ude) == 1 assert "Biotechnology and Related Fields" in series_ude[0].topic_data + @pytest.mark.anyio async def test_projects_trend_strategy(): strategy = ProjectsTrendStrategy() res = await strategy.get_trend( topics=["Biotechnology and Related Fields"], fuzzy=True, - institutions=["https://openalex.org/I62318514"] + institutions=["https://openalex.org/I62318514"], ) assert res is not None assert len(res.series) > 0 series_ude = [s for s in res.series if s.entity_id == "https://openalex.org/I62318514"] assert len(series_ude) == 1 assert "Biotechnology and Related Fields" in series_ude[0].topic_data + + +@pytest.mark.anyio +async def test_news_trend_strategy_fuzzy(): + strategy = NewsTrendStrategy() + res = await strategy.get_trend( + topics=["Artificial Intelligence"], + fuzzy=True, + ) + assert res is not None + assert len(res.series) > 0 + assert res.series[0].entity_name == "Artificial Intelligence" + + +@pytest.mark.anyio +async def test_news_trend_strategy_multi_topic(): + strategy = NewsTrendStrategy() + res = await strategy.get_trend( + topics=["Artificial Intelligence", "Robotics"], + fuzzy=True, + ) + assert res is not None + assert len(res.series) == 2 + s0 = res.series[0] + s1 = res.series[1] + assert s0.entity_name == "Artificial Intelligence" + assert s1.entity_name == "Robotics" + assert "Artificial Intelligence" in s0.topic_data + assert "Robotics" in s1.topic_data + + +@pytest.mark.anyio +async def test_all_trend_strategy(): + strategy = AllTrendStrategy() + res = await strategy.get_trend( + topics=["Artificial Intelligence"], + fuzzy=True, + institutions=["https://openalex.org/I62318514"], + ) + assert res is not None + assert len(res.series) >= 3 + + +@pytest.mark.anyio +async def test_autocomplete_locations(): + res = await autocomplete_locations("Germany") + assert isinstance(res, list) + + +@pytest.mark.anyio +async def test_get_top_institutions_by_region(): + res = await get_top_institutions_by_region( + topic="Artificial Intelligence", + country="DE", + limit=5, + ) + assert isinstance(res, list) + + +@pytest.mark.anyio +async def test_get_top_topics_for_entity(): + res = await get_top_topics_for_entity( + entity_id="https://openalex.org/I62318514", + entity_type="institution", + start_year=2015, + end_year=2024, + search_type="publications", + ) + assert isinstance(res, dict) + assert "items" in res + + +@pytest.mark.anyio +async def test_get_trend_data_delegation(): + res = await get_trend_data( + topics=["Artificial Intelligence"], + institutions=["https://openalex.org/I62318514"], + ) + 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 d6314793..74467758 100644 --- a/service/src/main/inse/university_ranking/trend_logic.py +++ b/service/src/main/inse/university_ranking/trend_logic.py @@ -1,178 +1,82 @@ import logging -import uuid import datetime from typing import List, Dict, Any, Optional -import numpy as np -from sklearn.preprocessing import MinMaxScaler +import asyncio -from sqlmodel import Session from inse.integrations import elasticsearch -from inse.model import ESIndex -from inse.auth.model import AccessToken, Organization +from inse.model import ESIndex, ESCluster from .model import ( TrendResponse, - TrendSeries, - TopicYearlyData, TopInstitutionItem, - AutocompleteLocationItem + AutocompleteLocationItem, +) +from .trend_query_builder import ( + TrendMetadataResolver, + TrendQueryBuilder, + clean_inst_id, + to_full_inst_url, + DEFAULT_INSTITUTION_ID, + DEFAULT_INSTITUTION_NAME, ) logger = logging.getLogger(__name__) -# Default fallback institution: University of Duisburg-Essen -DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" -DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" +DEFAULT_TOP_TOPICS_SIZE = 20 + async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: + """Returns country and continent options matching the autocomplete query using an ES multi-search.""" stripped = query.strip() if not stripped: return [] - import asyncio - - # Query countries index with alternatives and prefix boosts country_query = { - "bool": { - "should": [ - { - "match": { - "country_code": { - "query": stripped.upper(), - "boost": 20 - } - } - }, - { - "match_phrase_prefix": { - "display_name": { - "query": stripped, - "boost": 10 - } - } - }, - { - "match_phrase_prefix": { - "display_name_alternatives": { - "query": stripped, - "boost": 8 - } - } - }, - { - "match": { - "display_name": { - "query": stripped, - "boost": 5 - } - } - }, - { - "match": { - "display_name_alternatives": { - "query": stripped, - "boost": 4 - } - } - }, - { - "wildcard": { - "display_name.keyword": { - "value": f"*{stripped}*", - "case_insensitive": True, - "boost": 1 - } - } - }, - { - "wildcard": { - "display_name_alternatives.keyword": { - "value": f"*{stripped}*", - "case_insensitive": True, - "boost": 1 - } - } - } - ], - "minimum_should_match": 1 - } + "query": { + "bool": { + "should": [ + {"match": {"country_code": {"query": stripped.upper(), "boost": 20}}}, + {"match_phrase_prefix": {"display_name": {"query": stripped, "boost": 10}}}, + {"match_phrase_prefix": {"display_name_alternatives": {"query": stripped, "boost": 8}}}, + {"match": {"display_name": {"query": stripped, "boost": 5}}}, + {"match": {"display_name_alternatives": {"query": stripped, "boost": 4}}}, + {"wildcard": {"display_name.keyword": {"value": f"*{stripped}*", "case_insensitive": True, "boost": 1}}}, + {"wildcard": {"display_name_alternatives.keyword": {"value": f"*{stripped}*", "case_insensitive": True, "boost": 1}}}, + ], + "minimum_should_match": 1, + } + }, + "size": 10, + "_source": ["id", "display_name", "country_code", "wikidata_id"], } - # Query continents index continent_query = { - "bool": { - "should": [ - { - "match_phrase_prefix": { - "display_name": { - "query": stripped, - "boost": 10 - } - } - }, - { - "match_phrase_prefix": { - "display_name_alternatives": { - "query": stripped, - "boost": 8 - } - } - }, - { - "match": { - "display_name": { - "query": stripped, - "boost": 5 - } - } - }, - { - "match": { - "display_name_alternatives": { - "query": stripped, - "boost": 4 - } - } - }, - { - "wildcard": { - "display_name.keyword": { - "value": f"*{stripped}*", - "case_insensitive": True, - "boost": 1 - } - } - }, - { - "wildcard": { - "display_name_alternatives.keyword": { - "value": f"*{stripped}*", - "case_insensitive": True, - "boost": 1 - } - } - } - ], - "minimum_should_match": 1 - } + "query": { + "bool": { + "should": [ + {"match_phrase_prefix": {"display_name": {"query": stripped, "boost": 10}}}, + {"match_phrase_prefix": {"display_name_alternatives": {"query": stripped, "boost": 8}}}, + {"match": {"display_name": {"query": stripped, "boost": 5}}}, + {"match": {"display_name_alternatives": {"query": stripped, "boost": 4}}}, + {"wildcard": {"display_name.keyword": {"value": f"*{stripped}*", "case_insensitive": True, "boost": 1}}}, + {"wildcard": {"display_name_alternatives.keyword": {"value": f"*{stripped}*", "case_insensitive": True, "boost": 1}}}, + ], + "minimum_should_match": 1, + } + }, + "size": 5, + "_source": ["id", "display_name", "wikidata_id"], } try: - countries_res, continents_res = await asyncio.gather( - elasticsearch.search( - index=str(ESIndex.OPENALEX_COUNTRIES), - query=country_query, - size=10, - source=["id", "display_name", "country_code", "wikidata_id"], - cluster="nes" - ), - elasticsearch.search( - index=str(ESIndex.OPENALEX_CONTINENTS), - query=continent_query, - size=5, - source=["id", "display_name", "wikidata_id"], - cluster="nes" - ) + responses = await elasticsearch.msearch( + [ + (str(ESIndex.OPENALEX_COUNTRIES), country_query), + (str(ESIndex.OPENALEX_CONTINENTS), continent_query), + ], + cluster=ESCluster.NES, ) + countries_res = responses[0] if len(responses) > 0 else {} + continents_res = responses[1] if len(responses) > 1 else {} except Exception as e: logger.error("Failed to autocomplete locations in ES: %s", e) return [] @@ -183,591 +87,149 @@ async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]: for hit in continents_res.get("hits", {}).get("hits", []): source = hit["_source"] code_val = source.get("wikidata_id") or source["id"].split("/")[-1] - results.append(AutocompleteLocationItem( - id=code_val, - display_name=source["display_name"], - code=code_val, - type="continent" - )) + results.append( + AutocompleteLocationItem( + id=code_val, + display_name=source["display_name"], + code=code_val, + type="continent", + ) + ) # Process countries for hit in countries_res.get("hits", {}).get("hits", []): source = hit["_source"] - results.append(AutocompleteLocationItem( - id=source["country_code"], - display_name=source["display_name"], - code=source["country_code"], - type="country" - )) + results.append( + AutocompleteLocationItem( + id=source["country_code"], + display_name=source["display_name"], + code=source["country_code"], + type="country", + ) + ) return results - async def get_top_institutions_by_region( topic: str, region: Optional[str] = None, country: Optional[str] = None, - limit: int = 10 + limit: int = 10, ) -> List[TopInstitutionItem]: - """ - Search top educational institutions by region or country based on publication counts - for the specific topic, using a two-step Python-based sorting approach. - """ + """Search top educational institutions by region or country based on publication counts for the specific topic.""" country_codes = [] if country: country_codes = [country.upper()] elif region: - try: - # Query openalex-continents index to resolve continent country codes dynamically - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_CONTINENTS), - query={ - "bool": { - "should": [ - {"term": {"wikidata_id.keyword": region}}, - {"term": {"id": f"https://openalex.org/continents/{region}"}} - ] - } - }, - size=1, - source=["countries"], - cluster="nes" - ) - hits = res.get("hits", {}).get("hits", []) - if hits: - source = hits[0]["_source"] - country_codes = [ - c["id"].split("/")[-1].upper() for c in source.get("countries", []) - ] - except Exception as e: - logger.warning("Failed to resolve continent countries in get_top_institutions_by_region: %s", e) + meta_reg = await TrendMetadataResolver.resolve_all(query_regions=[region]) + continent_ccs = meta_reg.get("continent_country_codes", {}) + country_codes = continent_ccs.get(region, []) - # Resolve the topic to get the exact ID/display name - topic_filter = {"match_phrase": {"topics.display_name": topic}} - try: - topic_res = await elasticsearch.search( - index="openalex-topics", - query={"match_phrase": {"display_name": topic}}, - size=1, - source=["id", "display_name"], - cluster="nes" - ) - hits = topic_res.get("hits", {}).get("hits", []) - if hits: - source = hits[0]["_source"] - topic_id = source["id"] - topic_filter = {"term": {"topics.id.keyword": topic_id}} - except Exception as e: - logger.warning("Failed to resolve topic in get_top_institutions_by_region: %s", e) + meta_top = await TrendMetadataResolver.resolve_all(topics=[topic]) + topic_id = meta_top.get("resolved_topic_ids", {}).get(topic) + + topic_filter = ( + {"term": {"topics.id.keyword": topic_id}} + if topic_id + else {"match_phrase": {"topics.display_name": topic}} + ) - # Query openalex-institutions for educational entities matching country and topic must_clauses: List[Dict[str, Any]] = [ {"term": {"type": "education"}}, - topic_filter + topic_filter, ] - if country_codes: must_clauses.append({"terms": {"geo.country_code": country_codes}}) query = {"bool": {"filter": must_clauses}} - # Fetch top 500 by overall works count to cover a good pool of institutions - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_INSTITUTIONS), - query=query, - size=500, - source=["id", "display_name", "country_code", "works_count", "topics"], - sort=[{"works_count": "desc"}], - cluster="nes" - ) - - hits = res.get("hits", {}).get("hits", []) + # Stream candidate institutions using elasticsearch.scan to avoid hit limit cutoffs candidates = [] + try: + async for hit in elasticsearch.scan( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query=query, + source=["id", "display_name", "country_code", "works_count", "topics"], + cluster=ESCluster.NES, + ): + source = hit["_source"] + inst_id = source.get("id") + display_name = source.get("display_name", "Unknown") + country_code = source.get("country_code") + works_count = source.get("works_count") - for hit in hits: - source = hit["_source"] - inst_id = source.get("id") - display_name = source.get("display_name", "Unknown") - country_code = source.get("country_code") - works_count = source.get("works_count") + exact_topic_count = 0 + for t in source.get("topics", []): + if t.get("display_name", "").lower() == topic.lower() or (topic_id and t.get("id") == topic_id): + exact_topic_count = t.get("count", 0) + break - # Extract exact count for the selected topic - exact_topic_count = 0 - for t in source.get("topics", []): - if t.get("display_name", "").lower() == topic.lower(): - exact_topic_count = t.get("count", 0) - break - - candidates.append(TopInstitutionItem( - id=inst_id, - display_name=display_name, - country_code=country_code, - works_count=works_count, - exact_topic_count=exact_topic_count - )) + candidates.append( + TopInstitutionItem( + id=inst_id, + display_name=display_name, + country_code=country_code, + works_count=works_count, + exact_topic_count=exact_topic_count, + ) + ) + except Exception as e: + logger.error("Failed to fetch top institutions by region: %s", e) # Sort candidates by exact_topic_count descending candidates.sort(key=lambda x: x.exact_topic_count or 0, reverse=True) - return candidates[:limit] + async def get_trend_data( topics: List[str], institutions: Optional[List[str]] = None, countries: Optional[List[str]] = None, - regions: Optional[List[str]] = None + regions: Optional[List[str]] = None, ) -> TrendResponse: - """ - Traverses the openalex-works index to retrieve yearly contributions of selected/top - institutions, countries, and regions across multiple topics. - """ - if not topics: - return TrendResponse(series=[], years=[]) + """Retrieves publication trend data by delegating to PublicationsTrendStrategy.""" + from .trend_strategies import PublicationsTrendStrategy + strategy = PublicationsTrendStrategy() + return await strategy.get_trend( + topics=topics, + institutions=institutions, + countries=countries, + regions=regions, + ) - import asyncio - - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) - - # Resolve primary institution (default University of Duisburg-Essen for everyone) - primary_inst_id = DEFAULT_INSTITUTION_ID - primary_inst_name = DEFAULT_INSTITUTION_NAME - - # Initialize institutions list and ensure primary is included - query_institutions = [] - if institutions: - query_institutions = [i.strip() for i in institutions] - if primary_inst_id not in query_institutions: - query_institutions.insert(0, primary_inst_id) - - # Prepare lists of countries and regions dynamically - query_countries = countries or [] - query_regions = regions or [] - - clean_countries = [c.strip().upper() for c in query_countries] - clean_regions = [r.strip() for r in query_regions] - ids_to_resolve = list(set(query_institutions)) - - # Define concurrent metadata lookups - async def fetch_institutions(): - names = {primary_inst_id: primary_inst_name} - codes = {} - if not ids_to_resolve: - return names, codes - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_INSTITUTIONS), - query={"terms": {"id": ids_to_resolve}}, - size=len(ids_to_resolve), - source=["id", "display_name", "country_code"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - names[source["id"]] = source.get("display_name", source["id"]) - codes[source["id"]] = source.get("country_code", "") - except Exception as e: - logger.warning("Failed to resolve institution details from ES: %s", e) - return names, codes - - async def fetch_countries(): - names = {} - if not clean_countries: - return names - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_COUNTRIES), - query={"terms": {"country_code": clean_countries}}, - size=len(clean_countries), - source=["country_code", "display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - names[source["country_code"]] = source["display_name"] - except Exception as e: - logger.warning("Failed to resolve country names from ES: %s", e) - return names - - async def fetch_continents(): - names = {} - ccodes = {} - if not clean_regions: - return names, ccodes - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_CONTINENTS), - query={ - "bool": { - "should": [ - {"terms": {"wikidata_id.keyword": clean_regions}}, - {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} - ] - } - }, - size=len(clean_regions), - source=["id", "display_name", "wikidata_id", "countries"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - c_code = source.get("wikidata_id") or source["id"].split("/")[-1] - names[c_code] = source["display_name"] - ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])] - except Exception as e: - logger.warning("Failed to resolve continent names from ES: %s", e) - return names, ccodes - - async def fetch_topics(): - t_ids = {} - try: - res = await elasticsearch.search( - index="openalex-topics", - query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}}, - size=len(topics) * 2, - source=["id", "display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - for t in topics: - if t.lower() in source["display_name"].lower(): - t_ids[t] = source["id"] - except Exception as e: - logger.warning("Failed to resolve topic IDs from ES: %s", e) - return t_ids - - # Execute all 4 queries concurrently - ( - (resolved_names, resolved_country_codes), - resolved_country_names, - (resolved_continent_names, continent_country_codes), - resolved_topic_ids - ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics()) - - location_mappings = continent_country_codes.copy() - - # Map of filters inside our Elasticsearch aggregation - filters_map: Dict[str, Dict[str, Any]] = {} - - # 1. Institution Filters - for inst_id in query_institutions: - filters_map[f"inst_{inst_id}"] = { - "nested": { - "path": "authorships.institutions", - "query": { - "term": { - "authorships.institutions.id": inst_id - } - } - } - } - - # 2. Country Filters - for cc in clean_countries: - filters_map[f"country_{cc}"] = { - "nested": { - "path": "authorships.institutions", - "query": { - "term": { - "authorships.institutions.country_code": cc - } - } - } - } - - # 3. Continent/Region Filters - for r_code, member_ccs in continent_country_codes.items(): - if member_ccs: - filters_map[f"region_{r_code}"] = { - "nested": { - "path": "authorships.institutions", - "query": { - "terms": { - "authorships.institutions.country_code": member_ccs - } - } - } - } - - # If no entities specified, return empty - if not filters_map: - return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) - - # We will accumulate results in a nested structure: entity_key -> topic -> year -> (count, inst_count) - accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { - key: {t: {yr: (0, 1) for yr in years_range} for t in topics} - for key in filters_map - } - - # Build topic matching clauses and filters - topic_clauses = [] - topic_filters = {} - for t in topics: - tid = resolved_topic_ids.get(t) - if tid: - clause = { - "bool": { - "should": [ - {"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}}, - {"term": {"primary_topic.id": tid}} - ], - "minimum_should_match": 1 - } - } - else: - clause = { - "bool": { - "should": [ - {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}}, - {"match_phrase": {"primary_topic.display_name": t}} - ], - "minimum_should_match": 1 - } - } - topic_clauses.append(clause) - topic_filters[t] = clause - - # Build query-level entity filters to optimize search performance - entity_should_clauses = [] - if query_institutions: - entity_should_clauses.append({ - "nested": { - "path": "authorships.institutions", - "query": { - "terms": { - "authorships.institutions.id": query_institutions - } - } - } - }) - if clean_countries: - entity_should_clauses.append({ - "nested": { - "path": "authorships.institutions", - "query": { - "terms": { - "authorships.institutions.country_code": clean_countries - } - } - } - }) - all_continent_countries = [] - for member_ccs in continent_country_codes.values(): - all_continent_countries.extend(member_ccs) - if all_continent_countries: - entity_should_clauses.append({ - "nested": { - "path": "authorships.institutions", - "query": { - "terms": { - "authorships.institutions.country_code": list(set(all_continent_countries)) - } - } - } - }) - - # Construct the single-pass Elasticsearch query - filter_clauses = [ - { - "range": { - "publication_year": { - "gte": start_year, - "lte": end_year - } - } - }, - { - "bool": { - "should": topic_clauses, - "minimum_should_match": 1 - } - } - ] - if entity_should_clauses: - filter_clauses.append({ - "bool": { - "should": entity_should_clauses, - "minimum_should_match": 1 - } - }) - - query = { - "bool": { - "filter": filter_clauses - } - } - - # Build two-layer nested aggregations (topics -> entities -> publication_year) - aggregations = { - "topics_agg": { - "filters": { - "filters": topic_filters - }, - "aggs": { - "entities_agg": { - "filters": { - "filters": filters_map - }, - "aggs": { - "by_year": { - "terms": { - "field": "publication_year", - "size": len(years_range) * 2 - } - } - } - } - } - } - } - - try: - res = await elasticsearch.search( - index=f"{str(ESIndex.OPENALEX_WORKS)}*", - query=query, - body={"aggs": aggregations}, - size=0, - cluster="nes" - ) - - topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) - for t_name, t_bucket in topics_buckets.items(): - entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) - for entity_key, e_bucket in entities_buckets.items(): - year_buckets = e_bucket.get("by_year", {}).get("buckets", []) - for yr_bucket in year_buckets: - yr = int(yr_bucket.get("key")) - count = int(yr_bucket.get("doc_count", 0)) - inst_count = 1 - if yr in years_range: - accumulated_data[entity_key][t_name][yr] = (count, inst_count) - - except Exception as e: - logger.error("Error executing single-pass Elasticsearch query: %s", e) - - # Construct lists of raw counts and S-Curves for all series to normalize in parallel - series_keys = [] - raw_lists = [] - cumsum_lists = [] - inst_counts_map = {} - - for entity_key, topic_dict in accumulated_data.items(): - for topic, year_dict in topic_dict.items(): - raw_counts = [] - inst_counts = [] - for yr in years_range: - count, inst_count = year_dict[yr] - raw_counts.append(count) - inst_counts.append(inst_count) - - cumulative_counts = list(np.cumsum(raw_counts)) - - series_keys.append((entity_key, topic)) - raw_lists.append(raw_counts) - cumsum_lists.append(cumulative_counts) - inst_counts_map[(entity_key, topic)] = inst_counts - - normalized_lookup = {} - if raw_lists: - # Construct matrices of shape (n_years, n_series) - raw_matrix = np.array(raw_lists, dtype=float).T - cumsum_matrix = np.array(cumsum_lists, dtype=float).T - - # Batch normalize columns in parallel using MinMaxScaler - scaler_raw = MinMaxScaler() - normalized_matrix = scaler_raw.fit_transform(raw_matrix) - - scaler_cumsum = MinMaxScaler() - normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix) - - # Transpose back to lists of shape (n_series, n_years) - normalized_lists = normalized_matrix.T.tolist() - normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist() - - for idx, (entity_key, topic) in enumerate(series_keys): - normalized_lookup[(entity_key, topic)] = { - "normalized": normalized_lists[idx], - "cumulative": normalized_cumsum_lists[idx] - } - - # Process and build TrendSeries list - series_list: List[TrendSeries] = [] - - for entity_key, topic_dict in accumulated_data.items(): - # Resolve details for this entity - if entity_key.startswith("inst_"): - entity_id = entity_key[len("inst_"):] - entity_name = resolved_names.get(entity_id, entity_id) - entity_type = "institution" - elif entity_key.startswith("country_"): - entity_id = entity_key[len("country_"):] - entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") - entity_type = "country" - elif entity_key.startswith("region_"): - entity_id = entity_key[len("region_"):] - entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") - entity_type = "region" - else: - continue - - topic_data_map: Dict[str, List[TopicYearlyData]] = {} - - for topic, year_dict in topic_dict.items(): - yearly_data_items: List[TopicYearlyData] = [] - - lookup = normalized_lookup.get((entity_key, topic), {}) - norm_vals = lookup.get("normalized", [0.0] * len(years_range)) - cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) - inst_counts = inst_counts_map.get((entity_key, topic), [1] * len(years_range)) - - for idx, yr in enumerate(years_range): - count, _ = year_dict[yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=inst_counts[idx] - )) - - topic_data_map[topic] = yearly_data_items - - series_list.append(TrendSeries( - entity_id=entity_id, - entity_name=entity_name, - entity_type=entity_type, - country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, - topic_data=topic_data_map - )) - - return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) - -# Default fallback institution: University of Duisburg-Essen -DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" -DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" -DEFAULT_TOP_TOPICS_SIZE = 20 async def get_top_topics_for_entity( entity_id: str, entity_type: str, start_year: int, end_year: int, - search_type: str + search_type: str, ) -> Dict[str, Any]: + """Retrieves the top research topics for a specified entity and search type.""" if search_type == "patents" and entity_type == "institution": from inse.patents.org.logic import get_org_patents_by_institution_id try: - res = await get_org_patents_by_institution_id( - institution_id=entity_id, - match_type="all", - page=0, - size=10000 - ) - topic_counts = {} - for p in res.patents: + full_inst_id = to_full_inst_url(entity_id) + patents = [] + page = 0 + page_size = 1000 + while True: + res = await get_org_patents_by_institution_id( + institution_id=full_inst_id, + match_type="all", + page=page, + size=page_size, + ) + if not res or not res.patents: + break + patents.extend(res.patents) + if len(res.patents) < page_size or (res.total is not None and len(patents) >= res.total): + break + page += 1 + + topic_counts: Dict[str, int] = {} + for p in patents: try: yr = int(p.publication_year) if p.publication_year else None if yr and start_year <= yr <= end_year: @@ -776,17 +238,17 @@ async def get_top_topics_for_entity( topic_counts[ot.topic_display_name] = topic_counts.get(ot.topic_display_name, 0) + 1 except Exception: pass - + 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 patent topics for institution: %s", e) @@ -796,210 +258,16 @@ async def get_top_topics_for_entity( try: from inse.patents.search_client import PatentSearchClient patent_client = PatentSearchClient() - short_id = entity_id.split("/")[-1] - - aliases = [short_id, entity_id] - if entity_type == "institution": - try: - from inse.institutions.institutions_search_client import InstitutionsSearchClient - client = InstitutionsSearchClient() - resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(entity_id) - if resolved_aliases: - aliases = resolved_aliases - except Exception as e: - logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e) - - include_german = True - if entity_type == "country" and entity_id.strip().upper() != "DE": - include_german = False - elif entity_type == "region" and "DE" not in entity_id.strip().upper(): - include_german = False - project_ids_by_index = {} - - # 1. BUND - if include_german: - bund_filters = [] - if entity_type == "institution": - bund_filters.append({ - "bool": { - "should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases], - "minimum_should_match": 1 - } - }) - try: - bund_res = await patent_client._search( - index=ESIndex.PROJECTS_BUND_V1.value, - payload={ - "query": {"bool": {"filter": bund_filters}}, - "size": 10000, - "_source": ["_id"] - } - ) - p_ids = [h["_id"] for h in bund_res.get("hits", {}).get("hits", []) if "_id" in h] - if p_ids: - project_ids_by_index[ESIndex.PROJECTS_BUND_TOPICS.value] = p_ids - except Exception as e: - logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e) + short_id = clean_inst_id(entity_id) + full_id = to_full_inst_url(entity_id) - # 2. DFG - if include_german: - try: - dfg_pids = [] - if entity_type == "institution": - should_clauses = [{"match": {"root_name_en": {"query": alias, "operator": "and"}}} for alias in aliases] - dfg_inst_res = await patent_client._search( - index=ESIndex.DFG_INSTITUTES.value, - payload={"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}}, "size": 1000} - ) - for hit in dfg_inst_res.get("hits", {}).get("hits", []): - for p in hit.get("_source", {}).get("projects", []): - if p.get("project_id"): - dfg_pids.append(str(p["project_id"])) - if dfg_pids or entity_type != "institution": - dfg_filters = [] - if dfg_pids: - dfg_filters.append({"ids": {"values": dfg_pids}}) - dfg_res = await patent_client._search( - index=ESIndex.DFG_PROJECTS.value, - payload={"query": {"bool": {"filter": dfg_filters}}, "size": 10000, "_source": ["id"]} - ) - p_ids = [str(h["_source"]["id"]) for h in dfg_res.get("hits", {}).get("hits", []) if h.get("_source", {}).get("id")] - if p_ids: - project_ids_by_index[ESIndex.PROJECTS_DFG_TOPICS.value] = p_ids - except Exception as e: - logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e) - - # 3. EU CORDIS - 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), - (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value) - ] - for org_idx, proj_idx, topic_idx in eu_indices: - try: - filter_clauses = [] - if entity_type == "institution": - filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}}) - elif entity_type == "country": - filter_clauses.append({"term": {"country": entity_id.strip().upper()}}) - - eu_org_res = await patent_client._search( - index=org_idx.value, - payload={ - "query": {"bool": {"filter": filter_clauses}}, - "size": 0, - "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 - except Exception as e: - logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e) - - topic_counts = {} - for topic_idx, p_ids in project_ids_by_index.items(): - if not p_ids: - continue - for i in range(0, len(p_ids), 1000): - chunk = p_ids[i:i+1000] - payload = { - "query": {"terms": {"project_id": chunk}}, - "size": 0, - "aggs": { - "topic_matches": { - "nested": {"path": "topic_matches"}, - "aggs": { - "topics": { - "terms": {"field": "topic_matches.topic_display_name", "size": 100} - } - } - } - } - } - try: - res = await patent_client._search(index=topic_idx, payload=payload) - buckets = res.get("aggregations", {}).get("topic_matches", {}).get("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 topics from %s: %s", topic_idx, 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 project topics for entity: %s", e) - return {"items": []} -DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" -DEFAULT_TOP_TOPICS_SIZE = 20 - -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]: - if search_type == "patents" and entity_type == "institution": - from inse.patents.org.logic import get_org_patents_by_institution_id - try: - res = await get_org_patents_by_institution_id( - institution_id=entity_id, - match_type="all", - page=0, - size=10000 - ) - topic_counts = {} - for p in res.patents: - try: - yr = int(p.publication_year) if p.publication_year else None - if yr and start_year <= yr <= end_year: - for ot in p.openalex_topics: - if ot.topic_display_name: - topic_counts[ot.topic_display_name] = topic_counts.get(ot.topic_display_name, 0) + 1 - except Exception: - pass - - 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 patent topics for institution: %s", e) - return {"items": []} - - if search_type == "projects": - try: - from inse.patents.search_client import PatentSearchClient - patent_client = PatentSearchClient() - short_id = entity_id.split("/")[-1] - full_id = f"https://openalex.org/{short_id}" - aliases = [short_id, entity_id, full_id] if entity_type == "institution": try: from inse.institutions.institutions_search_client import InstitutionsSearchClient - client = InstitutionsSearchClient() - resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(short_id) + inst_client = InstitutionsSearchClient() + resolved_aliases = await inst_client.get_institution_aliases_by_oa_institution_id(short_id) if resolved_aliases: aliases.extend(resolved_aliases) @@ -1008,7 +276,7 @@ async def get_top_topics_for_entity( query={"terms": {"id": [full_id, short_id]}}, size=1, source=["display_name"], - cluster="nes" + cluster=ESCluster.NES, ) hits = inst_res.get("hits", {}).get("hits", []) if hits: @@ -1018,7 +286,7 @@ async def get_top_topics_for_entity( except Exception as e: logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e) - aliases = list(set([a for a in aliases if a])) + aliases = list(dict.fromkeys([a for a in aliases if a])) include_german = True if entity_type == "country" and entity_id.strip().upper() != "DE": @@ -1026,56 +294,64 @@ async def get_top_topics_for_entity( elif entity_type == "region" and "DE" not in entity_id.strip().upper(): include_german = False - project_ids_by_index = {} - - # 1. BUND + project_ids_by_index: Dict[str, List[str]] = {} + + # 1. BUND - use scan to retrieve all project IDs without 10k limits if include_german: bund_filters = [] if entity_type == "institution": bund_filters.append({ "bool": { "should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases], - "minimum_should_match": 1 + "minimum_should_match": 1, } }) try: - bund_res = await patent_client._search( + p_ids = [] + async for hit in elasticsearch.scan( index=ESIndex.PROJECTS_BUND_V1.value, - payload={ - "query": {"bool": {"filter": bund_filters}}, - "size": 10000, - "_source": ["_id"] - } - ) - p_ids = [h["_id"] for h in bund_res.get("hits", {}).get("hits", []) if "_id" in h] + query={"bool": {"filter": bund_filters}}, + source=["_id"], + cluster=ESCluster.INSE, + ): + if "_id" in hit: + p_ids.append(hit["_id"]) if p_ids: project_ids_by_index[ESIndex.PROJECTS_BUND_TOPICS.value] = p_ids except Exception as e: logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e) - # 2. DFG + # 2. DFG - scan institutes & projects if include_german: try: dfg_pids = [] if entity_type == "institution": should_clauses = [{"match": {"root_name_en": {"query": alias, "operator": "and"}}} for alias in aliases] - dfg_inst_res = await patent_client._search( + async for hit in elasticsearch.scan( index=ESIndex.DFG_INSTITUTES.value, - payload={"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}}, "size": 1000} - ) - for hit in dfg_inst_res.get("hits", {}).get("hits", []): + query={"bool": {"should": should_clauses, "minimum_should_match": 1}}, + source=["projects"], + cluster=ESCluster.INSE, + ): for p in hit.get("_source", {}).get("projects", []): if p.get("project_id"): dfg_pids.append(str(p["project_id"])) + if dfg_pids or entity_type != "institution": dfg_filters = [] if dfg_pids: dfg_filters.append({"ids": {"values": dfg_pids}}) - dfg_res = await patent_client._search( + + p_ids = [] + async for hit in elasticsearch.scan( index=ESIndex.DFG_PROJECTS.value, - payload={"query": {"bool": {"filter": dfg_filters}}, "size": 10000, "_source": ["id"]} - ) - p_ids = [str(h["_source"]["id"]) for h in dfg_res.get("hits", {}).get("hits", []) if h.get("_source", {}).get("id")] + query={"bool": {"filter": dfg_filters}}, + source=["id"], + cluster=ESCluster.INSE, + ): + pid = hit.get("_source", {}).get("id") + if pid: + p_ids.append(str(pid)) if p_ids: project_ids_by_index[ESIndex.PROJECTS_DFG_TOPICS.value] = p_ids except Exception as e: @@ -1085,7 +361,7 @@ async def get_top_topics_for_entity( 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), - (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value) + (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value), ] for org_idx, proj_idx, topic_idx in eu_indices: try: @@ -1094,14 +370,15 @@ async def get_top_topics_for_entity( filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}}) elif entity_type == "country": filter_clauses.append({"term": {"country": entity_id.strip().upper()}}) - + eu_org_res = await patent_client._search( index=org_idx.value, payload={ "query": {"bool": {"filter": filter_clauses}}, "size": 0, - "aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}} - } + "_source": False, + "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: @@ -1109,46 +386,54 @@ async def get_top_topics_for_entity( except Exception as e: logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e) - topic_counts = {} + # Batch multi-search for topic aggregation across chunks + topic_counts: Dict[str, int] = {} + msearch_queries = [] + for topic_idx, p_ids in project_ids_by_index.items(): if not p_ids: continue for i in range(0, len(p_ids), 1000): - chunk = p_ids[i:i+1000] + chunk = p_ids[i : i + 1000] payload = { "query": { "bool": { "should": [ {"terms": {"project_id": chunk}}, - {"terms": {"project_id.keyword": chunk}} + {"terms": {"project_id.keyword": chunk}}, ], - "minimum_should_match": 1 + "minimum_should_match": 1, } }, "size": 0, + "_source": False, "aggs": { "topics": { "terms": { "field": "topic_matches.topic_display_name.keyword", - "size": 100 + "size": 100, } } - } + }, } - try: - res = await patent_client._search(index=topic_idx, payload=payload) + msearch_queries.append((topic_idx, payload)) + + if msearch_queries: + try: + responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE) + for res in responses: buckets = res.get("aggregations", {}).get("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 topics from %s: %s", topic_idx, e) + except Exception as e: + logger.warning("Failed to aggregate topics via msearch: %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) @@ -1167,16 +452,17 @@ async def get_top_topics_for_entity( body={ "query": {"match_all": {}}, "size": 0, + "_source": False, "aggs": { "top_topics": { "terms": { "field": "topics.display_name.keyword", - "size": DEFAULT_TOP_TOPICS_SIZE + "size": DEFAULT_TOP_TOPICS_SIZE, } } - } + }, }, - cluster="inse" + cluster=ESCluster.INSE, ) buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", []) items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets] @@ -1192,62 +478,38 @@ async def get_top_topics_for_entity( return {"items": []} # Default fallback: openalex-works* query for publications/authors - # 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}" + entity_url = to_full_inst_url(entity_id) filter_clause = { "nested": { "path": "authorships.institutions", - "query": {"term": {"authorships.institutions.id": entity_url}} + "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()}" + entity_url = to_full_inst_url(entity_id) filter_clause = { "nested": { "path": "authorships", - "query": {"term": {"authorships.author.id": entity_url}} + "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()}} + "query": {"term": {"authorships.institutions.country_code": entity_id.strip().upper()}}, } } elif entity_type == "region": - ccs = [] - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_CONTINENTS), - query={ - "bool": { - "should": [ - {"term": {"wikidata_id.keyword": entity_id}}, - {"term": {"id": f"https://openalex.org/continents/{entity_id}"}} - ] - } - }, - size=1, - source=["countries"], - cluster="nes" - ) - hits = res.get("hits", {}).get("hits", []) - if hits: - source = hits[0]["_source"] - ccs = [ - c["id"].split("/")[-1].upper() for c in source.get("countries", []) - ] - except Exception as e: - logger.warning("Failed to resolve continent countries in get_top_topics_for_entity: %s", e) - + meta_reg = await TrendMetadataResolver.resolve_all(query_regions=[entity_id]) + ccs = meta_reg.get("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]}} + "query": {"terms": {"authorships.institutions.country_code": [c.upper() for c in ccs]}}, } } else: @@ -1257,7 +519,7 @@ async def get_top_topics_for_entity( "bool": { "filter": [ filter_clause, - {"range": {"publication_year": {"gte": start_year, "lte": end_year}}} + TrendQueryBuilder.build_date_range_filter("publication_year", start_year, end_year), ] } } @@ -1266,16 +528,16 @@ async def get_top_topics_for_entity( "top_topics": { "terms": { "field": "primary_topic.id", - "size": DEFAULT_TOP_TOPICS_SIZE + "size": DEFAULT_TOP_TOPICS_SIZE, }, "aggs": { "top_topic_hits": { "top_hits": { "size": 1, - "_source": ["primary_topic.display_name"] + "_source": ["primary_topic.display_name"], } } - } + }, } } @@ -1284,24 +546,23 @@ async def get_top_topics_for_entity( index="openalex-works*", body={"query": query, "aggs": aggs}, size=0, - cluster="nes" + cluster=ESCluster.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"] + hits = b.get("top_topic_hits", {}).get("hits", {}).get("hits", []) topic_name = "Unknown" - if hits: - topic_name = hits[0]["_source"]["primary_topic"]["display_name"] + if hits and "primary_topic" in hits[0]["_source"]: + topic_name = hits[0]["_source"]["primary_topic"].get("display_name", "Unknown") items.append({"name": topic_name, "count": doc_count}) - # Calculate "Other" - total_hits = res.get("hits", {}).get("total", {}).get("value", 0) + 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_slice = sum(b["count"] for b in items) - other_count = max(0, total_hits - sum_top_slice) + other_count = max(0, total_val - sum_top_slice) if other_count > 0: items.append({"name": "Andere Themen", "count": other_count}) diff --git a/service/src/main/inse/university_ranking/trend_query_builder.py b/service/src/main/inse/university_ranking/trend_query_builder.py new file mode 100644 index 00000000..ce7f0ed3 --- /dev/null +++ b/service/src/main/inse/university_ranking/trend_query_builder.py @@ -0,0 +1,307 @@ +import asyncio +import logging +from typing import Dict, List, Any, Optional, Tuple, Set +from inse.integrations import elasticsearch +from inse.model import ESIndex +logger = logging.getLogger(__name__) + +# Default fallback institution: University of Duisburg-Essen +DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514" +DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen" + + + +def clean_inst_id(id_str: str) -> str: + """Extracts short OpenAlex ID from full URL or returns as-is.""" + if not id_str: + return "" + s = id_str.strip() + return s.split("/")[-1] if "/" in s else s + + +def to_full_inst_url(id_str: str) -> str: + """Ensures institution ID is formatted as a full OpenAlex URL.""" + cleaned = clean_inst_id(id_str) + return f"https://openalex.org/{cleaned}" if cleaned else id_str + + +class TrendMetadataResolver: + """Centralized batch resolver for OpenAlex institutions, countries, continents, and topics.""" + + @staticmethod + async def resolve_all( + query_institutions: Optional[List[str]] = None, + query_countries: Optional[List[str]] = None, + query_regions: Optional[List[str]] = None, + topics: Optional[List[str]] = None, + include_aliases: bool = False, + ) -> Dict[str, Any]: + """Resolves metadata concurrently for entities.""" + institutions = query_institutions or [] + countries = [c.strip().upper() for c in (query_countries or []) if c.strip()] + regions = [r.strip() for r in (query_regions or []) if r.strip()] + topic_names = topics or [] + + # Prepare deduplicated OpenAlex institution IDs + inst_full_ids = list(set([to_full_inst_url(i) for i in institutions if i])) + + async def fetch_institutions(): + names: Dict[str, str] = {DEFAULT_INSTITUTION_ID: DEFAULT_INSTITUTION_NAME} + codes: Dict[str, str] = {} + aliases_map: Dict[str, List[str]] = {} + if not inst_full_ids: + return names, codes, aliases_map + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": inst_full_ids}}, + size=len(inst_full_ids), + source=["id", "display_name", "country_code"], + cluster="nes", + ) + for hit in res.get("hits", {}).get("hits", []): + src = hit["_source"] + full_id = src["id"] + short_id = clean_inst_id(full_id) + d_name = src.get("display_name", full_id) + c_code = src.get("country_code", "") + names[full_id] = d_name + names[short_id] = d_name + codes[full_id] = c_code + codes[short_id] = c_code + + if include_aliases: + from inse.institutions.institutions_search_client import InstitutionsSearchClient + inst_client = InstitutionsSearchClient() + + async def get_alias(inst_id_str: str) -> Tuple[str, List[str]]: + s_id = clean_inst_id(inst_id_str) + try: + resolved = await inst_client.get_institution_aliases_by_oa_institution_id(s_id) + return s_id, resolved or [names.get(s_id, s_id)] + except Exception as e: + logger.warning("Failed to resolve aliases for %s: %s", s_id, e) + return s_id, [names.get(s_id, s_id)] + + alias_results = await asyncio.gather(*(get_alias(i) for i in inst_full_ids)) + for short_id, alias_list in alias_results: + aliases_map[short_id] = alias_list + aliases_map[f"https://openalex.org/{short_id}"] = alias_list + + except Exception as e: + logger.warning("Failed to resolve institutions from ES: %s", e) + return names, codes, aliases_map + + async def fetch_countries(): + names: Dict[str, str] = {} + if not countries: + return names + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_COUNTRIES), + query={"terms": {"country_code": countries}}, + size=len(countries), + source=["country_code", "display_name"], + cluster="nes", + ) + for hit in res.get("hits", {}).get("hits", []): + src = hit["_source"] + names[src["country_code"]] = src["display_name"] + except Exception as e: + logger.warning("Failed to resolve countries from ES: %s", e) + return names + + async def fetch_continents(): + names: Dict[str, str] = {} + ccodes: Dict[str, List[str]] = {} + if not regions: + return names, ccodes + try: + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_CONTINENTS), + query={ + "bool": { + "should": [ + {"terms": {"wikidata_id.keyword": regions}}, + {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in regions]}}, + ] + } + }, + size=len(regions), + source=["id", "display_name", "wikidata_id", "countries"], + cluster="nes", + ) + for hit in res.get("hits", {}).get("hits", []): + src = hit["_source"] + c_code = src.get("wikidata_id") or src["id"].split("/")[-1] + names[c_code] = src["display_name"] + ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in src.get("countries", [])] + except Exception as e: + logger.warning("Failed to resolve continents from ES: %s", e) + return names, ccodes + + async def fetch_topics(): + topic_ids: Dict[str, str] = {} + if not topic_names: + return topic_ids + try: + res = await elasticsearch.search( + index="openalex-topics", + query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}}, + size=len(topic_names) * 2, + source=["id", "display_name"], + cluster="nes", + ) + for hit in res.get("hits", {}).get("hits", []): + src = hit["_source"] + d_name = src.get("display_name", "") + for t in topic_names: + if t.lower() in d_name.lower(): + topic_ids[t] = src["id"] + except Exception as e: + logger.warning("Failed to resolve topic IDs from ES: %s", e) + return topic_ids + + ( + (inst_names, inst_country_codes, inst_aliases), + country_names, + (continent_names, continent_country_codes), + resolved_topic_ids, + ) = await asyncio.gather( + fetch_institutions(), + fetch_countries(), + fetch_continents(), + fetch_topics(), + ) + + return { + "inst_names": inst_names, + "inst_country_codes": inst_country_codes, + "inst_aliases": inst_aliases, + "country_names": country_names, + "continent_names": continent_names, + "continent_country_codes": continent_country_codes, + "resolved_topic_ids": resolved_topic_ids, + } + + +class TrendQueryBuilder: + """Helper module for building standardized, modular Elasticsearch queries.""" + + @staticmethod + def build_topic_clause( + topic_display_name: str, + resolved_topic_id: Optional[str] = None, + keyword: Optional[str] = None, + fuzzy: bool = True, + ) -> Dict[str, Any]: + """Builds a topic or keyword matching clause.""" + if not fuzzy and keyword: + return { + "bool": { + "should": [ + {"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": keyword}}}}, + {"match_phrase": {"primary_topic.display_name": keyword}}, + {"match_phrase": {"display_name": keyword}}, + {"match_phrase": {"abstract": keyword}}, + ], + "minimum_should_match": 1, + } + } + elif resolved_topic_id: + return { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"term": {"topics.id": resolved_topic_id}}}}, + {"term": {"primary_topic.id": resolved_topic_id}}, + ], + "minimum_should_match": 1, + } + } + else: + return { + "bool": { + "should": [ + {"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": topic_display_name}}}}, + {"match_phrase": {"primary_topic.display_name": topic_display_name}}, + ], + "minimum_should_match": 1, + } + } + + @staticmethod + def build_date_range_filter(field_name: str, start_year: int, end_year: int) -> Dict[str, Any]: + """Builds a date range filter on publication_year or similar.""" + return { + "range": { + field_name: { + "gte": start_year, + "lte": end_year, + } + } + } + + @staticmethod + def build_entity_nested_filter( + inst_ids: Optional[List[str]] = None, + country_codes: Optional[List[str]] = None, + author_urls: Optional[List[str]] = None, + ) -> Dict[str, Any]: + """Builds a nested filter for OpenAlex works authorships/institutions.""" + should_clauses: List[Dict[str, Any]] = [] + + if inst_ids: + should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.id": inst_ids}}, + } + }) + + if country_codes: + should_clauses.append({ + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": country_codes}}, + } + }) + + if author_urls: + should_clauses.append({ + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": author_urls}}, + } + }) + + if not should_clauses: + return {"match_all": {}} + if len(should_clauses) == 1: + return should_clauses[0] + return {"bool": {"should": should_clauses, "minimum_should_match": 1}} + + @staticmethod + def build_trend_aggregations( + topic_filters: Dict[str, Dict[str, Any]], + entity_filters: Dict[str, Dict[str, Any]], + years_count: int, + ) -> Dict[str, Any]: + """Builds a two-layer nested aggregation (topics -> entities -> publication_year).""" + return { + "topics_agg": { + "filters": {"filters": topic_filters}, + "aggs": { + "entities_agg": { + "filters": {"filters": entity_filters}, + "aggs": { + "by_year": { + "terms": { + "field": "publication_year", + "size": years_count * 2, + } + } + }, + } + }, + } + } diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 4cf56e6e..ca60e79f 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -2,7 +2,7 @@ import abc import asyncio import logging import datetime -from typing import List, Dict, Any, Optional +from typing import List, Dict, Any, Optional, Tuple import numpy as np from sklearn.preprocessing import MinMaxScaler @@ -11,566 +11,19 @@ from inse.model import ESIndex, ESCluster from .model import ( TrendResponse, TrendSeries, - TopicYearlyData + TopicYearlyData, ) -from .trend_logic import ( +from .trend_query_builder import ( DEFAULT_INSTITUTION_ID, - DEFAULT_INSTITUTION_NAME + DEFAULT_INSTITUTION_NAME, + TrendMetadataResolver, + TrendQueryBuilder, + clean_inst_id, + to_full_inst_url, ) logger = logging.getLogger(__name__) -class TrendStrategy(abc.ABC): - @abc.abstractmethod - async def get_trend( - self, - topics: List[str], - keywords: Optional[List[str]] = None, - fuzzy: bool = True, - institutions: Optional[List[str]] = None, - countries: Optional[List[str]] = None, - regions: Optional[List[str]] = None, - authors: Optional[List[str]] = None, - ) -> TrendResponse: - pass - - def _normalize_series( - self, - years_range: List[int], - accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]], - topics: List[str] - ) -> Dict[tuple, Dict[str, List[float]]]: - series_keys = [] - raw_lists = [] - cumsum_lists = [] - - for entity_key, topic_dict in accumulated_data.items(): - for topic, year_dict in topic_dict.items(): - raw_counts = [] - for yr in years_range: - count, _ = year_dict[yr] - raw_counts.append(count) - - cumulative_counts = list(np.cumsum(raw_counts)) - series_keys.append((entity_key, topic)) - raw_lists.append(raw_counts) - cumsum_lists.append(cumulative_counts) - - normalized_lookup = {} - if raw_lists: - raw_matrix = np.array(raw_lists, dtype=float).T - cumsum_matrix = np.array(cumsum_lists, dtype=float).T - - scaler_raw = MinMaxScaler() - normalized_matrix = scaler_raw.fit_transform(raw_matrix) - - scaler_cumsum = MinMaxScaler() - normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix) - - normalized_lists = normalized_matrix.T.tolist() - normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist() - - for idx, (entity_key, topic) in enumerate(series_keys): - normalized_lookup[(entity_key, topic)] = { - "normalized": normalized_lists[idx], - "cumulative": normalized_cumsum_lists[idx] - } - return normalized_lookup - - -class PublicationsTrendStrategy(TrendStrategy): - async def get_trend( - self, - topics: List[str], - keywords: Optional[List[str]] = None, - fuzzy: bool = True, - institutions: Optional[List[str]] = None, - countries: Optional[List[str]] = None, - regions: Optional[List[str]] = None, - authors: Optional[List[str]] = None, - ) -> TrendResponse: - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) - - primary_inst_id = DEFAULT_INSTITUTION_ID - primary_inst_name = DEFAULT_INSTITUTION_NAME - - query_institutions = [] - if institutions: - query_institutions = [i.strip() for i in institutions] - if primary_inst_id not in query_institutions: - query_institutions.insert(0, primary_inst_id) - - query_countries = countries or [] - query_regions = regions or [] - - clean_countries = [c.strip().upper() for c in query_countries] - clean_regions = [r.strip() for r in query_regions] - ids_to_resolve = list(set(query_institutions)) - - # Resolution lookups - async def fetch_institutions(): - names = {primary_inst_id: primary_inst_name} - codes = {} - if not ids_to_resolve: - return names, codes - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_INSTITUTIONS), - query={"terms": {"id": ids_to_resolve}}, - size=len(ids_to_resolve), - source=["id", "display_name", "country_code"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - names[source["id"]] = source.get("display_name", source["id"]) - codes[source["id"]] = source.get("country_code", "") - except Exception as e: - logger.warning("Failed to resolve institution details from ES: %s", e) - return names, codes - - async def fetch_countries(): - names = {} - if not clean_countries: - return names - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_COUNTRIES), - query={"terms": {"country_code": clean_countries}}, - size=len(clean_countries), - source=["country_code", "display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - names[source["country_code"]] = source["display_name"] - except Exception as e: - logger.warning("Failed to resolve country names from ES: %s", e) - return names - - async def fetch_continents(): - names = {} - ccodes = {} - if not clean_regions: - return names, ccodes - try: - res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_CONTINENTS), - query={ - "bool": { - "should": [ - {"terms": {"wikidata_id.keyword": clean_regions}}, - {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} - ] - } - }, - size=len(clean_regions), - source=["id", "display_name", "wikidata_id", "countries"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - c_code = source.get("wikidata_id") or source["id"].split("/")[-1] - names[c_code] = source["display_name"] - ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])] - except Exception as e: - logger.warning("Failed to resolve continent names from ES: %s", e) - return names, ccodes - - async def fetch_topics(): - t_ids = {} - try: - res = await elasticsearch.search( - index="openalex-topics", - query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}}, - size=len(topics) * 2, - source=["id", "display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - for t in topics: - if t.lower() in source["display_name"].lower(): - t_ids[t] = source["id"] - except Exception as e: - logger.warning("Failed to resolve topic IDs from ES: %s", e) - return t_ids - - ( - (resolved_names, resolved_country_codes), - resolved_country_names, - (resolved_continent_names, continent_country_codes), - resolved_topic_ids - ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics()) - - location_mappings = continent_country_codes.copy() - - filters_map = {} - for inst_id in query_institutions: - filters_map[f"inst_{inst_id}"] = { - "nested": { - "path": "authorships.institutions", - "query": {"term": {"authorships.institutions.id": inst_id}} - } - } - for cc in clean_countries: - filters_map[f"country_{cc}"] = { - "nested": { - "path": "authorships.institutions", - "query": {"term": {"authorships.institutions.country_code": cc}} - } - } - for r_code, member_ccs in continent_country_codes.items(): - if member_ccs: - filters_map[f"region_{r_code}"] = { - "nested": { - "path": "authorships.institutions", - "query": {"terms": {"authorships.institutions.country_code": member_ccs}} - } - } - - if not filters_map: - return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) - - accumulated_data = { - key: {t: {yr: (0, 1) for yr in years_range} for t in topics} - for key in filters_map - } - - topic_clauses = [] - topic_filters = {} - for idx, t in enumerate(topics): - if not fuzzy and keywords and idx < len(keywords): - kw_val = keywords[idx] - clause = { - "bool": { - "should": [ - {"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw_val}}}}, - {"match_phrase": {"primary_topic.display_name": kw_val}}, - {"match_phrase": {"display_name": kw_val}}, - {"match_phrase": {"abstract": kw_val}} - ], - "minimum_should_match": 1 - } - } - else: - tid = resolved_topic_ids.get(t) - if tid: - clause = {"term": {"primary_topic.id": tid}} - else: - clause = {"match_phrase": {"primary_topic.display_name": t}} - topic_clauses.append(clause) - topic_filters[t] = clause - - entity_should_clauses = [] - if query_institutions: - entity_should_clauses.append({ - "nested": { - "path": "authorships.institutions", - "query": {"terms": {"authorships.institutions.id": query_institutions}} - } - }) - if clean_countries: - entity_should_clauses.append({ - "nested": { - "path": "authorships.institutions", - "query": {"terms": {"authorships.institutions.country_code": clean_countries}} - } - }) - all_continent_countries = [] - for member_ccs in continent_country_codes.values(): - all_continent_countries.extend(member_ccs) - if all_continent_countries: - entity_should_clauses.append({ - "nested": { - "path": "authorships.institutions", - "query": {"terms": {"authorships.institutions.country_code": list(set(all_continent_countries))}} - } - }) - - filter_clauses = [ - {"range": {"publication_year": {"gte": start_year, "lte": end_year}}}, - {"bool": {"should": topic_clauses, "minimum_should_match": 1}} - ] - if entity_should_clauses: - filter_clauses.append({"bool": {"should": entity_should_clauses, "minimum_should_match": 1}}) - - query = {"bool": {"filter": filter_clauses}} - aggregations = { - "topics_agg": { - "filters": {"filters": topic_filters}, - "aggs": { - "entities_agg": { - "filters": {"filters": filters_map}, - "aggs": { - "by_year": { - "terms": {"field": "publication_year", "size": len(years_range) * 2} - } - } - } - } - } - } - - try: - res = await elasticsearch.search( - index=f"{str(ESIndex.OPENALEX_WORKS)}*", - body={"query": query, "aggs": aggregations}, - size=0, - cluster="nes" - ) - topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) - for t_name, t_bucket in topics_buckets.items(): - entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) - for entity_key, e_bucket in entities_buckets.items(): - year_buckets = e_bucket.get("by_year", {}).get("buckets", []) - for yr_bucket in year_buckets: - yr = int(yr_bucket.get("key")) - count = int(yr_bucket.get("doc_count", 0)) - if yr in years_range: - accumulated_data[entity_key][t_name][yr] = (count, 1) - except Exception as e: - logger.error("Error executing Elasticsearch publication trend: %s", e) - - normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - - series_list = [] - for entity_key, topic_dict in accumulated_data.items(): - if entity_key.startswith("inst_"): - entity_id = entity_key[len("inst_"):] - entity_name = resolved_names.get(entity_id, entity_id) - entity_type = "institution" - elif entity_key.startswith("country_"): - entity_id = entity_key[len("country_"):] - entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") - entity_type = "country" - elif entity_key.startswith("region_"): - entity_id = entity_key[len("region_"):] - entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") - entity_type = "region" - else: - continue - - topic_data_map = {} - for topic, year_dict in topic_dict.items(): - yearly_data_items = [] - lookup = normalized_lookup.get((entity_key, topic), {}) - norm_vals = lookup.get("normalized", [0.0] * len(years_range)) - cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) - - for idx, yr in enumerate(years_range): - count, _ = year_dict[yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=1 - )) - topic_data_map[topic] = yearly_data_items - - series_list.append(TrendSeries( - entity_id=entity_id, - entity_name=entity_name, - entity_type=entity_type, - country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, - topic_data=topic_data_map - )) - - return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) - - -class AuthorsTrendStrategy(TrendStrategy): - async def get_trend( - self, - topics: List[str], - keywords: Optional[List[str]] = None, - fuzzy: bool = True, - institutions: Optional[List[str]] = None, - countries: Optional[List[str]] = None, - regions: Optional[List[str]] = None, - authors: Optional[List[str]] = None, - ) -> TrendResponse: - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) - - query_authors = authors or [] - if not query_authors: - 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_clean}}}, - size=len(query_authors_clean), - source=["display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - 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) - - # Fetch topic IDs - resolved_topic_ids = {} - try: - res = await elasticsearch.search( - index="openalex-topics", - query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}}, - size=len(topics) * 2, - source=["id", "display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - for t in topics: - if t.lower() in source["display_name"].lower(): - resolved_topic_ids[t] = source["id"] - except Exception as e: - logger.warning("Failed to resolve topic IDs from ES: %s", e) - - query_authors_full = [ - a if a.startswith("https://openalex.org/") else f"https://openalex.org/{a.upper()}" - for a in query_authors - ] - - filters_map = {} - for auth_id in query_authors: - auth_url = auth_id if auth_id.startswith("https://openalex.org/") else f"https://openalex.org/{auth_id.upper()}" - filters_map[f"author_{auth_id}"] = { - "nested": { - "path": "authorships", - "query": {"term": {"authorships.author.id": auth_url}} - } - } - - accumulated_data = { - key: {t: {yr: (0, 1) for yr in years_range} for t in topics} - for key in filters_map - } - - topic_clauses = [] - topic_filters = {} - for idx, t in enumerate(topics): - if not fuzzy and keywords and idx < len(keywords): - kw_val = keywords[idx] - clause = { - "bool": { - "should": [ - {"nested": {"path": "keywords", "query": {"match_phrase": {"keywords.display_name": kw_val}}}}, - {"match_phrase": {"primary_topic.display_name": kw_val}}, - {"match_phrase": {"display_name": kw_val}}, - {"match_phrase": {"abstract": kw_val}} - ], - "minimum_should_match": 1 - } - } - else: - tid = resolved_topic_ids.get(t) - if tid: - clause = {"term": {"primary_topic.id": tid}} - else: - clause = {"match_phrase": {"primary_topic.display_name": t}} - topic_clauses.append(clause) - topic_filters[t] = clause - - entity_should_clauses = [{ - "nested": { - "path": "authorships", - "query": {"terms": {"authorships.author.id": query_authors_full}} - } - }] - - filter_clauses = [ - {"range": {"publication_year": {"gte": start_year, "lte": end_year}}}, - {"bool": {"should": topic_clauses, "minimum_should_match": 1}}, - {"bool": {"should": entity_should_clauses, "minimum_should_match": 1}} - ] - - query = {"bool": {"filter": filter_clauses}} - aggregations = { - "topics_agg": { - "filters": {"filters": topic_filters}, - "aggs": { - "entities_agg": { - "filters": {"filters": filters_map}, - "aggs": { - "by_year": { - "terms": {"field": "publication_year", "size": len(years_range) * 2} - } - } - } - } - } - } - - try: - res = await elasticsearch.search( - index=f"{str(ESIndex.OPENALEX_WORKS)}*", - body={"query": query, "aggs": aggregations}, - size=0, - cluster="nes" - ) - topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) - for t_name, t_bucket in topics_buckets.items(): - entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) - for entity_key, e_bucket in entities_buckets.items(): - year_buckets = e_bucket.get("by_year", {}).get("buckets", []) - for yr_bucket in year_buckets: - yr = int(yr_bucket.get("key")) - count = int(yr_bucket.get("doc_count", 0)) - if yr in years_range: - accumulated_data[entity_key][t_name][yr] = (count, 1) - except Exception as e: - logger.error("Error executing Elasticsearch author trend: %s", e) - - normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - - series_list = [] - for entity_key, topic_dict in accumulated_data.items(): - entity_id = entity_key[len("author_"):] - entity_name = resolved_names.get(entity_id, entity_id) - - topic_data_map = {} - for topic, year_dict in topic_dict.items(): - yearly_data_items = [] - lookup = normalized_lookup.get((entity_key, topic), {}) - norm_vals = lookup.get("normalized", [0.0] * len(years_range)) - cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) - - for idx, yr in enumerate(years_range): - count, _ = year_dict[yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=1 - )) - topic_data_map[topic] = yearly_data_items - - series_list.append(TrendSeries( - entity_id=entity_id, - entity_name=entity_name, - entity_type="author", - topic_data=topic_data_map - )) - - return TrendResponse(series=series_list, years=years_range) - USPTO_PATENT_FIELDS = [ "title", "abstract", @@ -592,6 +45,406 @@ EPO_PATENT_FIELDS = [ "openalex_topics.topic_id", ] +DFG_INSTITUTION_FIELDS = [ + "Antragstellende Institution", + "Mitantragstellende Institution", + "Beteiligte Einrichtung", + "Beteiligte Hochschule", + "Beteiligte Institution", + "IGK-Partnerinstitution", + "Partnerorganisation", + "Unternehmen", +] + + +class TrendStrategy(abc.ABC): + @abc.abstractmethod + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + fuzzy: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + pass + + def _get_years_range(self, start_year: int = 2000) -> List[int]: + end_year = datetime.datetime.now().year - 1 + return list(range(start_year, end_year + 1)) + + def _normalize_series( + self, + years_range: List[int], + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]], + topics: List[str], + ) -> Dict[tuple, Dict[str, List[float]]]: + series_keys = [] + raw_lists = [] + cumsum_lists = [] + + for entity_key, topic_dict in accumulated_data.items(): + for topic, year_dict in topic_dict.items(): + raw_counts = [] + for yr in years_range: + count, _ = year_dict[yr] + raw_counts.append(count) + + cumulative_counts = list(np.cumsum(raw_counts)) + series_keys.append((entity_key, topic)) + raw_lists.append(raw_counts) + cumsum_lists.append(cumulative_counts) + + normalized_lookup = {} + if raw_lists: + raw_matrix = np.array(raw_lists, dtype=float).T + cumsum_matrix = np.array(cumsum_lists, dtype=float).T + + scaler_raw = MinMaxScaler() + normalized_matrix = scaler_raw.fit_transform(raw_matrix) + + scaler_cumsum = MinMaxScaler() + normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix) + + normalized_lists = normalized_matrix.T.tolist() + normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist() + + for idx, (entity_key, topic) in enumerate(series_keys): + normalized_lookup[(entity_key, topic)] = { + "normalized": normalized_lists[idx], + "cumulative": normalized_cumsum_lists[idx], + } + return normalized_lookup + + +class PublicationsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + fuzzy: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + years_range = self._get_years_range() + start_year, end_year = years_range[0], years_range[-1] + + query_institutions = [i.strip() for i in (institutions or []) if i.strip()] + if DEFAULT_INSTITUTION_ID not in query_institutions: + query_institutions.insert(0, DEFAULT_INSTITUTION_ID) + + meta = await TrendMetadataResolver.resolve_all( + query_institutions=query_institutions, + query_countries=countries, + query_regions=regions, + topics=topics, + ) + + resolved_names = meta["inst_names"] + resolved_country_codes = meta["inst_country_codes"] + resolved_country_names = meta["country_names"] + resolved_continent_names = meta["continent_names"] + continent_country_codes = meta["continent_country_codes"] + resolved_topic_ids = meta["resolved_topic_ids"] + + location_mappings = continent_country_codes.copy() + + filters_map: Dict[str, Dict[str, Any]] = {} + for inst_id in query_institutions: + full_url = to_full_inst_url(inst_id) + filters_map[f"inst_{full_url}"] = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.id": full_url}}, + } + } + + clean_countries = [c.strip().upper() for c in (countries or []) if c.strip()] + for cc in clean_countries: + filters_map[f"country_{cc}"] = { + "nested": { + "path": "authorships.institutions", + "query": {"term": {"authorships.institutions.country_code": cc}}, + } + } + + for r_code, member_ccs in continent_country_codes.items(): + if member_ccs: + filters_map[f"region_{r_code}"] = { + "nested": { + "path": "authorships.institutions", + "query": {"terms": {"authorships.institutions.country_code": member_ccs}}, + } + } + + if not filters_map: + return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) + + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + topic_clauses = [] + topic_filters = {} + for idx, t in enumerate(topics): + kw_val = keywords[idx] if (keywords and idx < len(keywords)) else None + clause = TrendQueryBuilder.build_topic_clause( + topic_display_name=t, + resolved_topic_id=resolved_topic_ids.get(t), + keyword=kw_val, + fuzzy=fuzzy, + ) + topic_clauses.append(clause) + topic_filters[t] = clause + + all_continent_countries = [] + for member_ccs in continent_country_codes.values(): + all_continent_countries.extend(member_ccs) + + inst_urls = [to_full_inst_url(i) for i in query_institutions] + entity_filter = TrendQueryBuilder.build_entity_nested_filter( + inst_ids=inst_urls, + country_codes=list(set(clean_countries + all_continent_countries)), + ) + + filter_clauses = [ + TrendQueryBuilder.build_date_range_filter("publication_year", start_year, end_year), + {"bool": {"should": topic_clauses, "minimum_should_match": 1}}, + entity_filter, + ] + + query = {"bool": {"filter": filter_clauses}} + aggregations = TrendQueryBuilder.build_trend_aggregations( + topic_filters=topic_filters, + entity_filters=filters_map, + years_count=len(years_range), + ) + + try: + res = await elasticsearch.search( + index=f"{str(ESIndex.OPENALEX_WORKS)}*", + body={"query": query, "aggs": aggregations}, + size=0, + cluster=ESCluster.NES, + ) + topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) + for t_name, t_bucket in topics_buckets.items(): + entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) + for entity_key, e_bucket in entities_buckets.items(): + year_buckets = e_bucket.get("by_year", {}).get("buckets", []) + for yr_bucket in year_buckets: + yr = int(yr_bucket.get("key")) + count = int(yr_bucket.get("doc_count", 0)) + if yr in years_range: + accumulated_data[entity_key][t_name][yr] = (count, 1) + except Exception as e: + logger.error("Error executing Elasticsearch publication trend: %s", e) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) + + series_list: List[TrendSeries] = [] + for entity_key, topic_dict in accumulated_data.items(): + if entity_key.startswith("inst_"): + entity_id = entity_key[len("inst_"):] + entity_name = resolved_names.get(entity_id, resolved_names.get(clean_inst_id(entity_id), entity_id)) + entity_type = "institution" + elif entity_key.startswith("country_"): + entity_id = entity_key[len("country_"):] + entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") + entity_type = "country" + elif entity_key.startswith("region_"): + entity_id = entity_key[len("region_"):] + entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") + entity_type = "region" + else: + continue + + topic_data_map: Dict[str, List[TopicYearlyData]] = {} + for topic, year_dict in topic_dict.items(): + yearly_data_items: List[TopicYearlyData] = [] + lookup = normalized_lookup.get((entity_key, topic), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + + for idx, yr in enumerate(years_range): + count, _ = year_dict[yr] + yearly_data_items.append( + TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1, + ) + ) + topic_data_map[topic] = yearly_data_items + + series_list.append( + TrendSeries( + entity_id=entity_id, + entity_name=entity_name, + entity_type=entity_type, + country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, + topic_data=topic_data_map, + ) + ) + + return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) + + +class AuthorsTrendStrategy(TrendStrategy): + async def get_trend( + self, + topics: List[str], + keywords: Optional[List[str]] = None, + fuzzy: bool = True, + institutions: Optional[List[str]] = None, + countries: Optional[List[str]] = None, + regions: Optional[List[str]] = None, + authors: Optional[List[str]] = None, + ) -> TrendResponse: + years_range = self._get_years_range() + start_year, end_year = years_range[0], years_range[-1] + + query_authors = authors or [] + if not query_authors: + return TrendResponse(series=[], years=years_range) + + query_authors_clean = [clean_inst_id(a).upper() for a in query_authors if a] + + # Resolve author display names + resolved_names: Dict[str, str] = {} + try: + res = await elasticsearch.search( + index="openalex-authors", + body={"query": {"ids": {"values": query_authors_clean}}}, + size=len(query_authors_clean), + source=["display_name"], + cluster=ESCluster.NES, + ) + for hit in res.get("hits", {}).get("hits", []): + 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) + + meta = await TrendMetadataResolver.resolve_all(topics=topics) + resolved_topic_ids = meta["resolved_topic_ids"] + + query_authors_full = [ + a if a.startswith("https://openalex.org/") else f"https://openalex.org/{clean_inst_id(a).upper()}" + for a in query_authors + ] + + filters_map: Dict[str, Dict[str, Any]] = {} + for auth_id, auth_url in zip(query_authors, query_authors_full): + filters_map[f"author_{auth_id}"] = { + "nested": { + "path": "authorships", + "query": {"term": {"authorships.author.id": auth_url}}, + } + } + + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + topic_clauses = [] + topic_filters = {} + for idx, t in enumerate(topics): + kw_val = keywords[idx] if (keywords and idx < len(keywords)) else None + clause = TrendQueryBuilder.build_topic_clause( + topic_display_name=t, + resolved_topic_id=resolved_topic_ids.get(t), + keyword=kw_val, + fuzzy=fuzzy, + ) + topic_clauses.append(clause) + topic_filters[t] = clause + + entity_filter = TrendQueryBuilder.build_entity_nested_filter(author_urls=query_authors_full) + + filter_clauses = [ + TrendQueryBuilder.build_date_range_filter("publication_year", start_year, end_year), + {"bool": {"should": topic_clauses, "minimum_should_match": 1}}, + entity_filter, + ] + + query = {"bool": {"filter": filter_clauses}} + aggregations = TrendQueryBuilder.build_trend_aggregations( + topic_filters=topic_filters, + entity_filters=filters_map, + years_count=len(years_range), + ) + + try: + res = await elasticsearch.search( + index=f"{str(ESIndex.OPENALEX_WORKS)}*", + body={"query": query, "aggs": aggregations}, + size=0, + cluster=ESCluster.NES, + ) + topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {}) + for t_name, t_bucket in topics_buckets.items(): + entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {}) + for entity_key, e_bucket in entities_buckets.items(): + year_buckets = e_bucket.get("by_year", {}).get("buckets", []) + for yr_bucket in year_buckets: + yr = int(yr_bucket.get("key")) + count = int(yr_bucket.get("doc_count", 0)) + if yr in years_range: + accumulated_data[entity_key][t_name][yr] = (count, 1) + except Exception as e: + logger.error("Error executing Elasticsearch author trend: %s", e) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) + + series_list: List[TrendSeries] = [] + for entity_key, topic_dict in accumulated_data.items(): + entity_id = entity_key[len("author_"):] + entity_name = resolved_names.get(entity_id, resolved_names.get(clean_inst_id(entity_id), entity_id)) + + topic_data_map: Dict[str, List[TopicYearlyData]] = {} + for topic, year_dict in topic_dict.items(): + yearly_data_items: List[TopicYearlyData] = [] + lookup = normalized_lookup.get((entity_key, topic), {}) + norm_vals = lookup.get("normalized", [0.0] * len(years_range)) + cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) + + for idx, yr in enumerate(years_range): + count, _ = year_dict[yr] + yearly_data_items.append( + TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1, + ) + ) + topic_data_map[topic] = yearly_data_items + + series_list.append( + TrendSeries( + entity_id=entity_id, + entity_name=entity_name, + entity_type="author", + topic_data=topic_data_map, + ) + ) + + return TrendResponse(series=series_list, years=years_range) + + class PatentsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -603,10 +456,7 @@ class PatentsTrendStrategy(TrendStrategy): regions: Optional[List[str]] = None, authors: Optional[List[str]] = None, ) -> TrendResponse: - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) - + years_range = self._get_years_range() primary_inst_id = DEFAULT_INSTITUTION_ID primary_inst_name = DEFAULT_INSTITUTION_NAME world_inst_id = "WORLD" @@ -617,18 +467,27 @@ class PatentsTrendStrategy(TrendStrategy): (world_inst_id, world_inst_name), ] - # 1. Fetch UDE patents using get_org_patents_by_institution_id + # 1. Fetch UDE patents without page limits / truncation from inse.patents.org.logic import get_org_patents_by_institution_id ude_patents = [] try: - res = await get_org_patents_by_institution_id( - institution_id=primary_inst_id, - match_type="all", - page=0, - size=10000, - ) - ude_patents = res.patents + # Stream all patent pages if multiple exist + page = 0 + page_size = 1000 + while True: + res = await get_org_patents_by_institution_id( + institution_id=primary_inst_id, + match_type="all", + page=page, + size=page_size, + ) + if not res or not res.patents: + break + ude_patents.extend(res.patents) + if len(res.patents) < page_size or (res.total is not None and len(ude_patents) >= res.total): + break + page += 1 except Exception as e: logger.error("Failed to fetch org-patents for UDE: %s", e) @@ -660,13 +519,9 @@ class PatentsTrendStrategy(TrendStrategy): return True return False - accumulated_data = { - f"inst_{primary_inst_id}": { - t: {yr: (0, 1) for yr in years_range} for t in topics - }, - f"inst_{world_inst_id}": { - t: {yr: (0, 1) for yr in years_range} for t in topics - }, + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { + f"inst_{primary_inst_id}": {t: {yr: (0, 1) for yr in years_range} for t in topics}, + f"inst_{world_inst_id}": {t: {yr: (0, 1) for yr in years_range} for t in topics}, } # Filter UDE patents per topic @@ -682,16 +537,18 @@ class PatentsTrendStrategy(TrendStrategy): except Exception: pass - # 2. Fetch Global / Rest der Welt patent counts via ES aggregations across EPO and USPTO + # 2. Fetch Global / Rest der Welt patent counts via ES multi-search (_msearch) + msearch_queries = [] + topic_search_indices = [] + for idx, t in enumerate(topics): - search_term = ( - t if fuzzy else (keywords[idx] if keywords and idx < len(keywords) else t) - ) + search_term = t if fuzzy else (keywords[idx] if keywords and idx < len(keywords) else t) if not search_term: continue uspto_query = { "size": 0, + "_source": False, "query": { "multi_match": { "query": search_term, @@ -700,15 +557,11 @@ class PatentsTrendStrategy(TrendStrategy): "operator": "or", } }, - "aggs": { - "by_year": { - "terms": {"field": "publication_year", "size": 50} - } - }, + "aggs": {"by_year": {"terms": {"field": "publication_year", "size": 100}}}, } - epo_query = { "size": 0, + "_source": False, "query": { "multi_match": { "query": search_term, @@ -717,63 +570,43 @@ class PatentsTrendStrategy(TrendStrategy): "operator": "or", } }, - "aggs": { - "by_year": { - "terms": {"field": "date_publication_year", "size": 50} - } - }, + "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)) + topic_search_indices.append(t) + + if msearch_queries: try: - uspto_res, epo_res = await asyncio.gather( - elasticsearch.search( - index="uspto_patents_3.0", - body=uspto_query, - cluster=ESCluster.INSE, - ), - elasticsearch.search( - index="epo_index_1.0", - body=epo_query, - cluster=ESCluster.INSE, - ), - return_exceptions=True, - ) - - if not isinstance(uspto_res, Exception): - buckets = uspto_res.get("aggregations", {}).get("by_year", {}).get("buckets", []) + responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE) + for i, res in enumerate(responses): + t_name = topic_search_indices[i // 2] + buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) for b in buckets: try: yr_val = int(b.get("key")) if yr_val in years_range: - cnt, _ = accumulated_data[f"inst_{world_inst_id}"][t][yr_val] - accumulated_data[f"inst_{world_inst_id}"][t][yr_val] = (cnt + int(b.get("doc_count", 0)), 1) + cnt, _ = accumulated_data[f"inst_{world_inst_id}"][t_name][yr_val] + accumulated_data[f"inst_{world_inst_id}"][t_name][yr_val] = ( + cnt + int(b.get("doc_count", 0)), + 1, + ) except Exception: pass - - if not isinstance(epo_res, Exception): - buckets = epo_res.get("aggregations", {}).get("by_year", {}).get("buckets", []) - for b in buckets: - try: - yr_val = int(b.get("key")) - if yr_val in years_range: - cnt, _ = accumulated_data[f"inst_{world_inst_id}"][t][yr_val] - accumulated_data[f"inst_{world_inst_id}"][t][yr_val] = (cnt + int(b.get("doc_count", 0)), 1) - except Exception: - pass - except Exception as exc: - logger.error("Failed to query global patent trends: %s", exc) + logger.error("Failed to query global patent trends via msearch: %s", exc) normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - series_list = [] + series_list: List[TrendSeries] = [] for inst_id, entity_name in series_entities: entity_key = f"inst_{inst_id}" topic_dict = accumulated_data[entity_key] - topic_data_map = {} + topic_data_map: Dict[str, List[TopicYearlyData]] = {} for topic, year_dict in topic_dict.items(): - yearly_data_items = [] + yearly_data_items: List[TopicYearlyData] = [] lookup = normalized_lookup.get((entity_key, topic), {}) norm_vals = lookup.get("normalized", [0.0] * len(years_range)) cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) @@ -801,22 +634,9 @@ class PatentsTrendStrategy(TrendStrategy): ) ) - return TrendResponse( - series=series_list, years=years_range, location_mappings={} - ) + return TrendResponse(series=series_list, years=years_range, location_mappings={}) -DFG_INSTITUTION_FIELDS = [ - "Antragstellende Institution", - "Mitantragstellende Institution", - "Beteiligte Einrichtung", - "Beteiligte Hochschule", - "Beteiligte Institution", - "IGK-Partnerinstitution", - "Partnerorganisation", - "Unternehmen", -] - class ProjectsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -828,147 +648,44 @@ class ProjectsTrendStrategy(TrendStrategy): regions: Optional[List[str]] = None, authors: Optional[List[str]] = None, ) -> TrendResponse: - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) - - primary_inst_id = DEFAULT_INSTITUTION_ID - primary_inst_name = DEFAULT_INSTITUTION_NAME - - def clean_inst_id(id_str: str) -> str: - return id_str.split("/")[-1] if id_str and "/" in id_str else id_str + years_range = self._get_years_range() + start_year, end_year = years_range[0], years_range[-1] primary_inst_short = clean_inst_id(DEFAULT_INSTITUTION_ID) - primary_inst_full = f"https://openalex.org/{primary_inst_short}" + primary_inst_full = to_full_inst_url(DEFAULT_INSTITUTION_ID) raw_insts = institutions or [] query_insts_short = [clean_inst_id(i) for i in raw_insts if i] if primary_inst_short not in query_insts_short: query_insts_short.insert(0, primary_inst_short) - # Preserve order while deduplicating - seen_insts = set() - dedup_inst_shorts = [] - for s_id in query_insts_short: - if s_id not in seen_insts: - seen_insts.add(s_id) - dedup_inst_shorts.append(s_id) + dedup_inst_shorts = list(dict.fromkeys(query_insts_short)) + ids_to_resolve = [to_full_inst_url(i) for i in dedup_inst_shorts] - query_institutions = dedup_inst_shorts - ids_to_resolve = [f"https://openalex.org/{i}" for i in query_institutions] + meta = await TrendMetadataResolver.resolve_all( + query_institutions=ids_to_resolve, + query_countries=countries, + query_regions=regions, + include_aliases=True, + ) - query_countries = countries or [] - query_regions = regions or [] - - clean_countries = [c.strip().upper() for c in query_countries] - clean_regions = [r.strip() for r in query_regions] - - # 1. Resolve institution names & aliases, country names, and regions - async def fetch_institutions(): - names = {primary_inst_full: DEFAULT_INSTITUTION_NAME, primary_inst_short: DEFAULT_INSTITUTION_NAME} - codes = {} - aliases_map = {} - if not ids_to_resolve: - return names, codes, aliases_map - try: - from inse.institutions.institutions_search_client import InstitutionsSearchClient - client = InstitutionsSearchClient() - res = await elasticsearch.search( - index=ESIndex.OPENALEX_INSTITUTIONS.value, - query={"terms": {"id": ids_to_resolve}}, - size=len(ids_to_resolve), - source=["id", "display_name", "country_code"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - full_id = source["id"] - short_id = clean_inst_id(full_id) - d_name = source.get("display_name", full_id) - c_code = source.get("country_code", "") - names[full_id] = d_name - names[short_id] = d_name - codes[full_id] = c_code - codes[short_id] = c_code - - async def get_aliases(inst_short_id): - try: - resolved = await client.get_institution_aliases_by_oa_institution_id(inst_short_id) - return inst_short_id, resolved or [names.get(inst_short_id, inst_short_id)] - except Exception as e: - logger.warning("Failed to get aliases for %s: %s", inst_short_id, e) - return inst_short_id, [names.get(inst_short_id, inst_short_id)] - - alias_results = await asyncio.gather(*(get_aliases(i) for i in query_institutions)) - for inst_short_id, aliases in alias_results: - aliases_map[inst_short_id] = aliases - aliases_map[f"https://openalex.org/{inst_short_id}"] = aliases - except Exception as e: - logger.warning("Failed to resolve institution details from ES: %s", e) - return names, codes, aliases_map - - async def fetch_countries(): - names = {} - if not clean_countries: - return names - try: - res = await elasticsearch.search( - index=ESIndex.OPENALEX_COUNTRIES.value, - query={"terms": {"country_code": clean_countries}}, - size=len(clean_countries), - source=["country_code", "display_name"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - names[source["country_code"]] = source["display_name"] - except Exception as e: - logger.warning("Failed to resolve country names from ES: %s", e) - return names - - async def fetch_continents(): - names = {} - ccodes = {} - if not clean_regions: - return names, ccodes - try: - res = await elasticsearch.search( - index=ESIndex.OPENALEX_CONTINENTS.value, - query={ - "bool": { - "should": [ - {"terms": {"wikidata_id.keyword": clean_regions}}, - {"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}} - ] - } - }, - size=len(clean_regions), - source=["id", "display_name", "wikidata_id", "countries"], - cluster="nes" - ) - for hit in res.get("hits", {}).get("hits", []): - source = hit["_source"] - c_code = source.get("wikidata_id") or source["id"].split("/")[-1] - names[c_code] = source["display_name"] - ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])] - except Exception as e: - logger.warning("Failed to resolve continent names from ES: %s", e) - return names, ccodes - - ( - (resolved_names, resolved_country_codes, resolved_aliases), - resolved_country_names, - (resolved_continent_names, continent_country_codes) - ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents()) + resolved_names = meta["inst_names"] + resolved_country_codes = meta["inst_country_codes"] + resolved_aliases = meta["inst_aliases"] + resolved_country_names = meta["country_names"] + resolved_continent_names = meta["continent_names"] + continent_country_codes = meta["continent_country_codes"] location_mappings = continent_country_codes.copy() - # Build list of entities - filters_map = {} - for inst_id in query_institutions: + filters_map: Dict[str, Tuple[str, Any]] = {} + for inst_id in dedup_inst_shorts: filters_map[f"inst_{inst_id}"] = ("institution", inst_id) + + clean_countries = [c.strip().upper() for c in (countries or []) if c.strip()] for cc in clean_countries: filters_map[f"country_{cc}"] = ("country", cc) + for r_code, member_ccs in continent_country_codes.items(): if member_ccs: filters_map[f"region_{r_code}"] = ("region", member_ccs) @@ -979,133 +696,105 @@ class ProjectsTrendStrategy(TrendStrategy): from inse.patents.search_client import PatentSearchClient patent_client = PatentSearchClient() - # Resolve DFG project IDs for institutions using dfg_institutes_2.0 root_name_en matches - dfg_institution_projects = {} - async def resolve_dfg_projects_for_inst(inst_id): + # Resolve DFG project IDs for institutions via scan/search without size limit cutoffs + dfg_institution_projects: Dict[str, List[str]] = {} + + async def resolve_dfg_projects(inst_id: str) -> Tuple[str, List[str]]: aliases = resolved_aliases.get(inst_id, []) if not aliases: return inst_id, [] - - should_clauses = [] - for alias in aliases: - should_clauses.append({ - "match": { - "root_name_en": { - "query": alias, - "operator": "and" - } - } - }) + should_clauses = [{"match": {"root_name_en": {"query": alias, "operator": "and"}}} for alias in aliases] try: - res = await patent_client._search( + p_ids = set() + async for hit in elasticsearch.scan( index=ESIndex.DFG_INSTITUTES.value, - payload={ - "query": { - "bool": { - "should": should_clauses, - "minimum_should_match": 1 - } - }, - "size": 1000 - } - ) - hits = res.get("hits", {}).get("hits", []) - p_ids = [] - for hit in hits: - source = hit.get("_source", {}) - for p in source.get("projects", []): + query={"bool": {"should": should_clauses, "minimum_should_match": 1}}, + source=["projects"], + cluster=ESCluster.INSE, + ): + for p in hit.get("_source", {}).get("projects", []): pid = p.get("project_id") if pid: - p_ids.append(str(pid)) - return inst_id, list(set(p_ids)) + p_ids.add(str(pid)) + return inst_id, list(p_ids) except Exception as e: - logger.warning("Failed to query dfg_institutes_2.0 for %s: %s", inst_id, e) + logger.warning("Failed to query dfg_institutes for %s: %s", inst_id, e) return inst_id, [] - if query_institutions: - dfg_resolve_results = await asyncio.gather(*( - resolve_dfg_projects_for_inst(inst_id) for inst_id in query_institutions - )) + if dedup_inst_shorts: + dfg_resolve_results = await asyncio.gather(*(resolve_dfg_projects(i) for i in dedup_inst_shorts)) for inst_id, p_ids in dfg_resolve_results: dfg_institution_projects[inst_id] = p_ids - # 2. Fetch matched project IDs for each topic (if fuzzy is True) - topic_project_ids = {} + # Fetch matched project IDs for each topic using elasticsearch.scan (uncapped full retrieval) + topic_project_ids: Dict[str, Dict[str, List[str]]] = {} indices_mapping = { - ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value: (ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS), - ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value: (ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS), - ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value: (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS), + ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value: ( + ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, + ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, + ), + ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value: ( + ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, + ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, + ), + ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value: ( + ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, + ESIndex.CORDIS_EU_FP7_PROJECTS, + ), ESIndex.PROJECTS_BUND_TOPICS.value: (ESIndex.PROJECTS_BUND_V1, None), - ESIndex.PROJECTS_DFG_TOPICS.value: (ESIndex.DFG_PROJECTS, None) + ESIndex.PROJECTS_DFG_TOPICS.value: (ESIndex.DFG_PROJECTS, None), } if fuzzy: - for idx, t in enumerate(topics): + for t in topics: topic_project_ids[t] = {ind: [] for ind in indices_mapping} - map_query = { - "query": { - "term": { - "topic_matches.topic_display_name.keyword": t - } - }, - "size": 10000 - } + map_query = {"term": {"topic_matches.topic_display_name.keyword": t}} - map_tasks = [] - ind_list = list(indices_mapping.keys()) - for ind in ind_list: - map_tasks.append(patent_client._search(index=ind, payload=map_query)) + async def scan_topic_projects(mapping_index: str) -> Tuple[str, List[str]]: + p_ids = set() + try: + async for hit in elasticsearch.scan( + index=mapping_index, + query=map_query, + source=["project_id"], + cluster=ESCluster.INSE, + ): + pid = hit.get("_source", {}).get("project_id") + if pid: + p_ids.add(str(pid)) + except Exception as ex: + logger.warning("Failed scanning project topic mapping index %s: %s", mapping_index, ex) + return mapping_index, list(p_ids) - map_responses = await asyncio.gather(*map_tasks, return_exceptions=True) - for m_idx, res_map in enumerate(map_responses): - if isinstance(res_map, Exception): - logger.warning("Failed to query mapping index %s: %s", ind_list[m_idx], res_map) - continue - hits = res_map.get("hits", {}).get("hits", []) - p_ids = [h["_source"]["project_id"] for h in hits if h.get("_source", {}).get("project_id")] - topic_project_ids[t][ind_list[m_idx]] = p_ids + scan_results = await asyncio.gather(*(scan_topic_projects(ind) for ind in indices_mapping)) + for ind_name, p_ids in scan_results: + topic_project_ids[t][ind_name] = p_ids - # 3. For each entity & topic, filter actual indices and aggregate - accumulated_data = { + accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = { key: {t: {yr: (0, 1) for yr in years_range} for t in topics} for key in filters_map } - async def query_project_trends(entity_key, entity_type, entity_val, topic, keyword): - # Fetch entity_project_ids for EU cordis indices (HEU, H2020, FP7) - async def get_eu_entity_project_ids(org_index): + 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] - } - }) + 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 - } - }, + "query": {"bool": {"filter": filter_clauses}}, "size": 0, - "aggs": { - "project_ids": { - "terms": { - "field": "projectID", - "size": 65536 - } - } - } - } + "_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] @@ -1114,44 +803,44 @@ class ProjectsTrendStrategy(TrendStrategy): return [] eu_indices = [ - (ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, "projects_cordiseu_heurope_openalex_topics"), - (ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, "projects_cordiseu_h2020_openalex_topics"), - (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, "projects_cordiseu_fp7_openalex_topics") + ( + ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, + ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, + "projects_cordiseu_heurope_openalex_topics", + ), + ( + ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, + ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, + "projects_cordiseu_h2020_openalex_topics", + ), + ( + ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, + ESIndex.CORDIS_EU_FP7_PROJECTS, + "projects_cordiseu_fp7_openalex_topics", + ), ] - - eu_org_tasks = [get_eu_entity_project_ids(org_idx) for org_idx, _, _ in eu_indices] - eu_org_ids_list = await asyncio.gather(*eu_org_tasks) - + + eu_org_ids_list = await asyncio.gather(*(get_eu_entity_project_ids(org_idx) for org_idx, _, _ in eu_indices)) actual_tasks = [] - - # 1. BUND + + # BUND include_bund = True if entity_type == "country" and entity_val != "DE": include_bund = False elif entity_type == "region" and "DE" not in entity_val: include_bund = False - + if include_bund: 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 + "should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases], + "minimum_should_match": 1, } }) - + if fuzzy: p_ids = topic_project_ids[topic].get("projects_bund_openalex_topics", []) if p_ids: @@ -1170,30 +859,32 @@ class ProjectsTrendStrategy(TrendStrategy): {"match": {"Thema": keyword}}, {"match": {"Klartext Leistungsplansystematik": keyword}}, {"match": {"Förderprofil": keyword}}, - {"match": {"Leistungsplansystematik_fullname": keyword}} + {"match": {"Leistungsplansystematik_fullname": keyword}}, ], - "minimum_should_match": 1 + "minimum_should_match": 1, } } ] + bund_filters } } } - + if bund_query: bund_payload = { **bund_query, "size": 0, + "_source": False, "aggs": { "projects_by_year": { "date_histogram": { "field": "funding_start", "calendar_interval": "year", - "format": "yyyy" + "format": "yyyy", } } - } + }, } + async def process_bund(): try: res = await patent_client._search(index=ESIndex.PROJECTS_BUND_V1.value, payload=bund_payload) @@ -1201,15 +892,16 @@ class ProjectsTrendStrategy(TrendStrategy): except Exception as e: logger.warning("Failed to query BUND projects: %s", e) return "date", [] + actual_tasks.append(process_bund()) - # 2. DFG + # DFG include_dfg = True if entity_type == "country" and entity_val != "DE": include_dfg = False elif entity_type == "region" and "DE" not in entity_val: include_dfg = False - + if include_dfg: dfg_filters = [] dfg_inst_pids = None @@ -1235,7 +927,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": [ @@ -1248,12 +940,7 @@ class ProjectsTrendStrategy(TrendStrategy): {"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": "publications", "query": {"match": {"publications.title": keyword}}}}, { "nested": { "path": "subject_classification", @@ -1262,15 +949,15 @@ class ProjectsTrendStrategy(TrendStrategy): "should": [ {"match": {"subject_classification.fach": keyword}}, {"match": {"subject_classification.fachkollegium": keyword}}, - {"match": {"subject_classification.wissenschaftsbereich": keyword}} + {"match": {"subject_classification.wissenschaftsbereich": keyword}}, ], - "minimum_should_match": 1 + "minimum_should_match": 1, } - } + }, } - } + }, ], - "minimum_should_match": 1 + "minimum_should_match": 1, } }) @@ -1278,15 +965,10 @@ class ProjectsTrendStrategy(TrendStrategy): dfg_payload = { "query": {"bool": {"filter": dfg_filters}}, "size": 0, - "aggs": { - "projects_by_year": { - "terms": { - "field": "funding_start", - "size": 100 - } - } - } + "_source": False, + "aggs": {"projects_by_year": {"terms": {"field": "funding_start", "size": 100}}}, } + async def process_dfg(): try: res = await patent_client._search(index=ESIndex.DFG_PROJECTS.value, payload=dfg_payload) @@ -1294,14 +976,15 @@ class ProjectsTrendStrategy(TrendStrategy): except Exception as e: logger.warning("Failed to query DFG projects: %s", e) return "terms", [] + actual_tasks.append(process_dfg()) - # 3. 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: continue - + if fuzzy: p_ids = topic_project_ids[topic].get(mapping_key, []) common_ids = list(set(p_ids) & set(entity_project_ids)) @@ -1317,32 +1000,31 @@ class ProjectsTrendStrategy(TrendStrategy): {"terms": {"id": entity_project_ids}}, { "bool": { - "should": [ - {"match": {"title": keyword}}, - {"match": {"objective": keyword}} - ], - "minimum_should_match": 1 + "should": [{"match": {"title": keyword}}, {"match": {"objective": keyword}}], + "minimum_should_match": 1, } - } + }, ] } } } - + if proj_query: proj_payload = { **proj_query, "size": 0, + "_source": False, "aggs": { "projects_by_year": { "date_histogram": { "field": "startDate", "calendar_interval": "year", - "format": "yyyy" + "format": "yyyy", } } - } + }, } + async def process_cordis(p_idx=proj_index, payload=proj_payload): try: res = await patent_client._search(index=p_idx.value, payload=payload) @@ -1350,13 +1032,14 @@ class ProjectsTrendStrategy(TrendStrategy): 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 = {} + year_counts: Dict[int, int] = {} for agg_type, buckets in results: for b in buckets: if agg_type == "date": @@ -1368,7 +1051,7 @@ class ProjectsTrendStrategy(TrendStrategy): year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0) except ValueError: pass - else: # terms + else: yr_val = b.get("key") if yr_val is not None: try: @@ -1391,12 +1074,12 @@ class ProjectsTrendStrategy(TrendStrategy): normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - series_list = [] + series_list: List[TrendSeries] = [] for entity_key, topic_dict in accumulated_data.items(): entity_type, entity_val = filters_map[entity_key] if entity_type == "institution": - entity_id = entity_val if entity_val.startswith("http") else f"https://openalex.org/{entity_val}" - entity_name = resolved_names.get(entity_val, entity_val).split("/")[-1] + entity_id = to_full_inst_url(entity_val) + entity_name = resolved_names.get(entity_val, resolved_names.get(clean_inst_id(entity_val), entity_val)) elif entity_type == "country": entity_id = entity_val entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") @@ -1404,35 +1087,39 @@ class ProjectsTrendStrategy(TrendStrategy): entity_id = entity_key[len("region_"):] entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") - topic_data_map = {} + topic_data_map: Dict[str, List[TopicYearlyData]] = {} for topic, year_dict in topic_dict.items(): - yearly_data_items = [] + yearly_data_items: List[TopicYearlyData] = [] lookup = normalized_lookup.get((entity_key, topic), {}) norm_vals = lookup.get("normalized", [0.0] * len(years_range)) cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) for idx, yr in enumerate(years_range): count, _ = year_dict[yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=1 - )) + yearly_data_items.append( + TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1, + ) + ) topic_data_map[topic] = yearly_data_items - series_list.append(TrendSeries( - entity_id=entity_id, - entity_name=entity_name, - entity_type=entity_type, - country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, - topic_data=topic_data_map - )) + series_list.append( + TrendSeries( + entity_id=entity_id, + entity_name=entity_name, + entity_type=entity_type, + country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None, + topic_data=topic_data_map, + ) + ) return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) -### requires proper index (currently only workaround) + class NewsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -1444,11 +1131,9 @@ class NewsTrendStrategy(TrendStrategy): regions: Optional[List[str]] = None, authors: Optional[List[str]] = None, ) -> TrendResponse: - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) + years_range = self._get_years_range() + start_year, end_year = years_range[0], years_range[-1] - # Each series entity represents one topic/keyword. accumulated_data = { f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics} for t in topics @@ -1457,7 +1142,7 @@ class NewsTrendStrategy(TrendStrategy): 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"} - # Query UDE news postprocessed index to get matching news IDs without 10k capping + # Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]: if fuzzy: term = t_name @@ -1472,13 +1157,13 @@ class NewsTrendStrategy(TrendStrategy): term = t_name es_query = {"match": {"keywords": term}} - news_ids = set() + news_ids: Set[str] = set() try: async for hit in elasticsearch.scan( index="aktuell_postproc", query=es_query, source=["news_id"], - cluster="inse" + cluster=ESCluster.INSE, ): nid = hit.get("_source", {}).get("news_id") if nid: @@ -1493,14 +1178,14 @@ class NewsTrendStrategy(TrendStrategy): "query_string": { "query": term, "fields": AKTUELLES_SEARCH_FIELDS, - "default_operator": "AND" + "default_operator": "AND", } } async for hit in elasticsearch.scan( index="aktuell", query=content_query, source=["news_id"], - cluster="inse" + cluster=ESCluster.INSE, ): nid = hit.get("_id") or hit.get("_source", {}).get("news_id") if nid: @@ -1510,85 +1195,83 @@ class NewsTrendStrategy(TrendStrategy): return list(news_ids) - # Find all matching news IDs concurrently - matching_ids_list = await asyncio.gather(*[ - fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics) - ]) + matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics))) async def count_by_year(t_name: str, news_ids: List[str]): if not news_ids: return entity_key = f"news_topic_{t_name}" - # Batch news_ids in chunks of 2000 to avoid ES query clause limits - for i in range(0, len(news_ids), 2000): - chunk = news_ids[i:i+2000] - try: - res = await elasticsearch.search( - index="aktuell", - body={ - "query": {"bool": {"filter": [ - {"ids": {"values": chunk}}, - {"range": {"date_year": {"gte": start_year, "lte": end_year}}} - ]}}, - "aggs": { - "by_year": { - "terms": {"field": "date_year", "size": len(years_range) * 2} - } - } - }, - size=0, - cluster="inse" - ) - buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) - for b in buckets: - yr = int(b.get("key")) - count = int(b.get("doc_count", 0)) - if yr in years_range: - prev_count, _ = accumulated_data[entity_key][t_name][yr] - accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) - except Exception as e: - logger.warning("Failed to aggregate news years from ES for chunk: %s", e) - # Aggregate news publication years concurrently - await asyncio.gather(*[ - count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list) - ]) + # Prepare multi-search payloads for chunks of news_ids to avoid payload limits + chunk_queries = [] + for i in range(0, len(news_ids), 2000): + chunk = news_ids[i : i + 2000] + q_body = { + "query": { + "bool": { + "filter": [ + {"ids": {"values": chunk}}, + TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year), + ] + } + }, + "aggs": {"by_year": {"terms": {"field": "date_year", "size": len(years_range) * 2}}}, + "size": 0, + "_source": False, + } + chunk_queries.append(("aktuell", q_body)) + + if chunk_queries: + try: + responses = await elasticsearch.msearch(chunk_queries, cluster=ESCluster.INSE) + for res in responses: + buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", []) + for b in buckets: + yr = int(b.get("key")) + count = int(b.get("doc_count", 0)) + if yr in years_range: + prev_count, _ = accumulated_data[entity_key][t_name][yr] + accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1) + except Exception as e: + logger.warning("Failed to aggregate news years from ES via msearch: %s", e) + + await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list))) normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) - series_list = [] + series_list: List[TrendSeries] = [] for t_name in topics: entity_key = f"news_topic_{t_name}" - topic_data_map = {} + topic_data_map: Dict[str, List[TopicYearlyData]] = {} - # Extract yearly data items for t_name from accumulated_data[entity_key][t_name] lookup = normalized_lookup.get((entity_key, t_name), {}) norm_vals = lookup.get("normalized", [0.0] * len(years_range)) cum_vals = lookup.get("cumulative", [0.0] * len(years_range)) - yearly_data_items = [] + yearly_data_items: List[TopicYearlyData] = [] for idx, yr in enumerate(years_range): count, _ = accumulated_data[entity_key][t_name][yr] - yearly_data_items.append(TopicYearlyData( - year=yr, - raw=count, - normalized=norm_vals[idx], - cumulative=cum_vals[idx], - institutions_count=1 - )) + yearly_data_items.append( + TopicYearlyData( + year=yr, + raw=count, + normalized=norm_vals[idx], + cumulative=cum_vals[idx], + institutions_count=1, + ) + ) - # Populate topic_data_map for ALL topic keys in topics with t_name's yearly items. - # This ensures uni-trend-chart accessing topic_data[selectedTopic] for any selected topic - # always gets t_name's true data items for series t_name. for topic in topics: topic_data_map[topic] = yearly_data_items - series_list.append(TrendSeries( - entity_id=entity_key, - entity_name=t_name, - entity_type="institution", - topic_data=topic_data_map - )) + series_list.append( + TrendSeries( + entity_id=entity_key, + entity_name=t_name, + entity_type="institution", + topic_data=topic_data_map, + ) + ) return TrendResponse(series=series_list, years=years_range) @@ -1604,9 +1287,9 @@ class AllTrendStrategy(TrendStrategy): regions: Optional[List[str]] = None, authors: Optional[List[str]] = None, ) -> TrendResponse: - target_inst = institutions[0] if institutions and len(institutions) > 0 else DEFAULT_INSTITUTION_ID - short_id = target_inst.split("/")[-1].upper() - is_ude = (short_id == "I62318514") + target_inst = institutions[0] if (institutions and len(institutions) > 0) else DEFAULT_INSTITUTION_ID + short_id = clean_inst_id(target_inst).upper() + is_ude = short_id == "I62318514" pub_strat = PublicationsTrendStrategy() pat_strat = PatentsTrendStrategy() @@ -1615,7 +1298,7 @@ class AllTrendStrategy(TrendStrategy): tasks = [ pub_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]), pat_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]), - proj_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]) + proj_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]), ] if is_ude: @@ -1628,18 +1311,16 @@ class AllTrendStrategy(TrendStrategy): proj_res = results[2] news_res = results[3] if is_ude else None - start_year = 2000 - end_year = datetime.datetime.now().year - 1 - years_range = list(range(start_year, end_year + 1)) + years_range = self._get_years_range() pub_series = pub_res.series[0] if pub_res.series else None pat_series = pat_res.series[0] if pat_res.series else None proj_series = proj_res.series[0] if proj_res.series else None - composite_series = [] + composite_series: List[TrendSeries] = [] def add_composite(series_obj: Optional[TrendSeries], c_id: str, c_name: str): - topic_data_map = {} + topic_data_map: Dict[str, List[TopicYearlyData]] = {} for topic in topics: if series_obj and topic in series_obj.topic_data: topic_data_map[topic] = series_obj.topic_data[topic] @@ -1648,19 +1329,21 @@ class AllTrendStrategy(TrendStrategy): TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1) for yr in years_range ] - composite_series.append(TrendSeries( - entity_id=c_id, - entity_name=c_name, - entity_type="institution", - topic_data=topic_data_map - )) + composite_series.append( + TrendSeries( + entity_id=c_id, + entity_name=c_name, + entity_type="institution", + topic_data=topic_data_map, + ) + ) add_composite(pub_series, "publications", "Akademische Publikationen") add_composite(pat_series, "patents", "Patentanmeldungen") add_composite(proj_series, "projects", "Drittmittelförderung") if is_ude and news_res: - merged_news_topic_data = {} + merged_news_topic_data: Dict[str, List[TopicYearlyData]] = {} for topic in topics: term_key = f"news_topic_{topic}" matching_series = next((s for s in news_res.series if s.entity_id == term_key), None) @@ -1676,7 +1359,7 @@ class AllTrendStrategy(TrendStrategy): entity_id="news", entity_name="UDE Campus Aktuell Beiträge", entity_type="institution", - topic_data=merged_news_topic_data + topic_data=merged_news_topic_data, ) add_composite(news_series, "news", "UDE Campus Aktuell Beiträge")