full refactor of trend logic, added multisearch and count method to general elastic tools, added tests for the other strategies #238

Merged
kuzko merged 1 commits from feature/Keyword_search_rework into dev 2026-07-24 13:23:47 +02:00
5 changed files with 1485 additions and 1992 deletions
@@ -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
@@ -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
File diff suppressed because it is too large Load Diff
@@ -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,
}
}
},
}
},
}
}
File diff suppressed because it is too large Load Diff