attempt to optimize backend search time and small modeltype changes

This commit is contained in:
Kazgatari
2026-07-06 10:20:42 +02:00
parent 2703f46575
commit b5d03c84c4
4 changed files with 311 additions and 132 deletions
@@ -12,7 +12,7 @@ END_YEAR = datetime.datetime.now().year - 1
async def resolve_topic(topic_query: str) -> Topic:
"""Resolves a topic display name or ID using Elasticsearch with source whitelisting."""
if topic_query.startswith("http") or "/T" in topic_query:
if topic_query.startswith("https://openalex.org/"):
query = {"term": {"id": topic_query}}
else:
query = {"match_phrase": {"display_name": topic_query}}
@@ -40,12 +40,17 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking
topic_obj = await resolve_topic(topic_query)
topic_name = topic_obj.display_name or topic_query
if topic_obj.id:
topic_filter = {"term": {"topics.id.keyword": topic_obj.id}}
else:
topic_filter = {"match_phrase": {"topics.display_name": topic_name}}
query = {
"bool": {
"must": [
"filter": [
{"term": {"type": "education"}},
{"term": {"geo.country_code": "DE"}},
{"match_phrase": {"topics.display_name": topic_name}}
topic_filter
]
}
}
@@ -106,7 +111,7 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking
}
}
# Topic filter clause (using topic ID if resolved, otherwise matching phrase)
# Topic filter clause (using topic ID if resolved, otherwise matching display name keyword)
topic_id = topic_obj.id
if topic_id:
topic_clause = {
@@ -129,10 +134,10 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking
}
}
# Construct single-pass ES query on openalex-works
# Construct single-pass ES query on openalex-works in Filter Context
works_query = {
"bool": {
"must": [
"filter": [
{
"range": {
"publication_year": {
@@ -141,7 +146,17 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking
}
}
},
topic_clause
topic_clause,
{
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [inst["id"] for inst in top_10]
}
}
}
}
]
}
}
@@ -175,6 +190,7 @@ async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> Ranking
query=works_query,
body={"aggs": aggregations},
size=0,
cluster="nes"
)
@@ -125,20 +125,61 @@ async def get_top_institutions_by_region(
"""
country_codes = []
if country:
country_codes = [country]
country_codes = [country.upper()]
elif region:
country_codes = REGION_MAPPINGS.get(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)
# 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)
# Query openalex-institutions for educational entities matching country and topic
must_clauses: List[Dict[str, Any]] = [
{"term": {"type": "education"}},
{"match_phrase": {"topics.display_name": topic}}
topic_filter
]
if country_codes:
must_clauses.append({"terms": {"geo.country_code": country_codes}})
query = {"bool": {"must": must_clauses}}
query = {"bool": {"filter": must_clauses}}
# Fetch top 50 by overall works count to cover a good pool of institutions
res = await elasticsearch.search(
@@ -193,8 +234,10 @@ async def get_trend_data(
if not topics:
return TrendResponse(series=[], years=[])
import asyncio
start_year = 2000
end_year = datetime.datetime.now().year -1
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)
@@ -208,61 +251,67 @@ async def get_trend_data(
if primary_inst_id not in query_institutions:
query_institutions.insert(0, primary_inst_id)
# Resolve institution names and country codes from openalex-institutions
resolved_names: Dict[str, str] = {primary_inst_id: primary_inst_name}
resolved_country_codes: Dict[str, str] = {}
# 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))
if ids_to_resolve:
# 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:
name_res = await elasticsearch.search(
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 name_res.get("hits", {}).get("hits", []):
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
resolved_names[source["id"]] = source.get("display_name", source["id"])
resolved_country_codes[source["id"]] = source.get("country_code", "")
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
# Prepare lists of countries and regions dynamically
query_countries = countries or []
query_regions = regions or []
resolved_country_names: Dict[str, str] = {}
clean_countries: List[str] = []
if query_countries:
clean_countries = [c.split("/")[-1].upper() for c in query_countries]
async def fetch_countries():
names = {}
if not clean_countries:
return names
try:
c_res = await elasticsearch.search(
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 c_res.get("hits", {}).get("hits", []):
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
resolved_country_names[source["country_code"]] = source["display_name"]
names[source["country_code"]] = source["display_name"]
except Exception as e:
logger.warning("Failed to resolve country names from ES: %s", e)
return names
resolved_continent_names: Dict[str, str] = {}
continent_country_codes: Dict[str, List[str]] = {}
location_mappings: Dict[str, List[str]] = {}
if query_regions:
clean_regions = [r.split("/")[-1] for r in query_regions]
async def fetch_continents():
names = {}
ccodes = {}
if not clean_regions:
return names, ccodes
try:
r_res = await elasticsearch.search(
res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_CONTINENTS),
query={
"bool": {
"should": [
{"terms": {"wikidata_id": clean_regions}},
{"terms": {"wikidata_id.keyword": clean_regions}},
{"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}}
]
}
@@ -271,43 +320,47 @@ async def get_trend_data(
source=["id", "display_name", "wikidata_id", "countries"],
cluster="nes"
)
for hit in r_res.get("hits", {}).get("hits", []):
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
c_code = source.get("wikidata_id") or source["id"].split("/")[-1]
resolved_continent_names[c_code] = source["display_name"]
member_ccs = [
c["id"].split("/")[-1].upper() for c in source.get("countries", [])
]
continent_country_codes[c_code] = member_ccs
location_mappings[c_code] = member_ccs
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]] = {}
# Resolve the topic IDs from the openalex-topics index to enable fast term queries
resolved_topic_ids: Dict[str, str] = {}
try:
topic_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 topic_res.get("hits", {}).get("hits", []):
source = hit["_source"]
resolved_topic_ids[source["display_name"]] = source["id"]
except Exception as e:
logger.warning("Failed to resolve topic IDs from ES: %s", e)
# 1. Institution Filters
for inst_id in query_institutions:
filters_map[f"inst_{inst_id}"] = {
@@ -426,7 +479,7 @@ async def get_trend_data(
})
# Construct the single-pass Elasticsearch query
must_clauses = [
filter_clauses = [
{
"range": {
"publication_year": {
@@ -443,7 +496,7 @@ async def get_trend_data(
}
]
if entity_should_clauses:
must_clauses.append({
filter_clauses.append({
"bool": {
"should": entity_should_clauses,
"minimum_should_match": 1
@@ -452,7 +505,7 @@ async def get_trend_data(
query = {
"bool": {
"must": must_clauses
"filter": filter_clauses
}
}
@@ -600,3 +653,4 @@ async def get_trend_data(
))
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)