attempt to optimize backend search time and small modeltype changes
This commit is contained in:
@@ -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)
|
||||
|
||||
|
||||
+12
-2
@@ -147,9 +147,13 @@
|
||||
@for (result of searchResults(); track result.id) {
|
||||
<li>
|
||||
<button
|
||||
(click)="addInstitution(result.id, result.display_name)">
|
||||
(click)="
|
||||
addInstitution(result.id || '', result.display_name || '')
|
||||
">
|
||||
<span class="name">{{ result.display_name }}</span>
|
||||
<span class="hint">{{ result.hint || result.type }}</span>
|
||||
<span class="hint">{{
|
||||
result.hint || result.entity_type
|
||||
}}</span>
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
@@ -217,6 +221,12 @@
|
||||
title="Shows total absolute publication counts.">
|
||||
📊 Total Volume
|
||||
</button>
|
||||
<button
|
||||
[class.active]="chartMode() === 'cumulative'"
|
||||
(click)="setChartMode('cumulative')"
|
||||
title="Shows normalized cumulative publications growth (S-Curve).">
|
||||
📈 S-Curve (Normalized)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+158
-59
@@ -12,6 +12,15 @@ import {
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatAutocompleteModule } from '@angular/material/autocomplete';
|
||||
import { UniTrendChartComponent } from '../uni-trend-chart/uni-trend-chart.component';
|
||||
import {
|
||||
TrendResponse,
|
||||
@@ -20,14 +29,32 @@ import {
|
||||
TopInstitutionItem,
|
||||
AutocompleteLocationItem,
|
||||
AutocompleteResponse,
|
||||
AutocompleteResponseResultsInner,
|
||||
UniversityRankingsService,
|
||||
InstitutionsService,
|
||||
} from '../../../api';
|
||||
|
||||
export interface CompareItem {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-uni-trend-parent',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, UniTrendChartComponent],
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
UniTrendChartComponent,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
MatCheckboxModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatAutocompleteModule,
|
||||
],
|
||||
templateUrl: './uni-trend-parent.component.html',
|
||||
styleUrl: './uni-trend-parent.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
@@ -47,19 +74,23 @@ export class UniTrendParentComponent implements OnInit {
|
||||
readonly primaryInstitutionName = signal<string>(
|
||||
'University of Duisburg-Essen',
|
||||
);
|
||||
readonly comparisonInstitutions = signal<{ id: string; name: string }[]>([]);
|
||||
readonly comparisonCountries = signal<{ id: string; name: string }[]>([]);
|
||||
readonly comparisonRegions = signal<{ id: string; name: string }[]>([]);
|
||||
readonly startYear = signal<number>(2015);
|
||||
readonly endYear = signal<number>(new Date().getFullYear() - 1);
|
||||
readonly chartMode = signal<'normalized' | 'total'>('total');
|
||||
readonly comparisonInstitutions = signal<CompareItem[]>([]);
|
||||
readonly comparisonCountries = signal<CompareItem[]>([
|
||||
{ id: 'DE', name: 'Germany' },
|
||||
]);
|
||||
readonly comparisonRegions = signal<CompareItem[]>([]);
|
||||
readonly startYear = signal<number>(2010);
|
||||
readonly endYear = signal<number>(2025);
|
||||
readonly chartMode = signal<'normalized' | 'total' | 'cumulative'>(
|
||||
'normalized',
|
||||
);
|
||||
readonly activeChartTopic = signal<string>('');
|
||||
|
||||
// Cached parameters of the last active search request to track "isDirty"
|
||||
readonly fetchedTopics = signal<string[]>([]);
|
||||
readonly fetchedInstitutions = signal<{ id: string; name: string }[]>([]);
|
||||
readonly fetchedCountries = signal<{ id: string; name: string }[]>([]);
|
||||
readonly fetchedRegions = signal<{ id: string; name: string }[]>([]);
|
||||
readonly fetchedInstitutions = signal<CompareItem[]>([]);
|
||||
readonly fetchedCountries = signal<CompareItem[]>([]);
|
||||
readonly fetchedRegions = signal<CompareItem[]>([]);
|
||||
|
||||
// Results & Loading signals
|
||||
readonly rawTrendResponse = signal<TrendResponse | null>(null);
|
||||
@@ -69,7 +100,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
|
||||
// Autocomplete UI state
|
||||
readonly searchQuery = signal<string>('');
|
||||
readonly searchResults = signal<any[]>([]);
|
||||
readonly searchResults = signal<AutocompleteResponseResultsInner[]>([]);
|
||||
readonly locationQuery = signal<string>('');
|
||||
readonly locationSearchResults = signal<AutocompleteLocationItem[]>([]);
|
||||
|
||||
@@ -82,13 +113,13 @@ export class UniTrendParentComponent implements OnInit {
|
||||
if (!raw) return null;
|
||||
|
||||
const currentInstIds = new Set(
|
||||
this.comparisonInstitutions().map((i) => i.id.toLowerCase()),
|
||||
this.comparisonInstitutions().map((i: CompareItem) => i.id.toLowerCase()),
|
||||
);
|
||||
const currentCountryIds = new Set(
|
||||
this.comparisonCountries().map((c) => c.id.toLowerCase()),
|
||||
this.comparisonCountries().map((c: CompareItem) => c.id.toLowerCase()),
|
||||
);
|
||||
const currentRegionIds = new Set(
|
||||
this.comparisonRegions().map((r) => r.id.toLowerCase()),
|
||||
this.comparisonRegions().map((r: CompareItem) => r.id.toLowerCase()),
|
||||
);
|
||||
const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase();
|
||||
|
||||
@@ -97,17 +128,9 @@ export class UniTrendParentComponent implements OnInit {
|
||||
if (s.entity_type === 'institution') {
|
||||
return id === defaultInstId || currentInstIds.has(id);
|
||||
} else if (s.entity_type === 'country') {
|
||||
return (
|
||||
currentCountryIds.has(id) ||
|
||||
currentCountryIds.has('https://openalex.org/countries/' + id) ||
|
||||
Array.from(currentCountryIds).some((cid) => cid.endsWith('/' + id))
|
||||
);
|
||||
return currentCountryIds.has(id);
|
||||
} else if (s.entity_type === 'region') {
|
||||
return (
|
||||
currentRegionIds.has(id) ||
|
||||
currentRegionIds.has('https://openalex.org/continents/' + id) ||
|
||||
Array.from(currentRegionIds).some((rid) => rid.endsWith('/' + id))
|
||||
);
|
||||
return currentRegionIds.has(id);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
@@ -121,31 +144,31 @@ export class UniTrendParentComponent implements OnInit {
|
||||
// Computed dirty state to enable "Search" button
|
||||
readonly isDirty = computed(() => {
|
||||
const fetchedInsts = this.fetchedInstitutions()
|
||||
.map((i) => i.id)
|
||||
.map((i: CompareItem) => i.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
const currentInsts = this.comparisonInstitutions()
|
||||
.map((i) => i.id)
|
||||
.map((i: CompareItem) => i.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
if (fetchedInsts !== currentInsts) return true;
|
||||
|
||||
const fetchedC = this.fetchedCountries()
|
||||
.map((c) => c.id)
|
||||
.map((c: CompareItem) => c.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
const currentC = this.comparisonCountries()
|
||||
.map((c) => c.id)
|
||||
.map((c: CompareItem) => c.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
if (fetchedC !== currentC) return true;
|
||||
|
||||
const fetchedR = this.fetchedRegions()
|
||||
.map((r) => r.id)
|
||||
.map((r: CompareItem) => r.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
const currentR = this.comparisonRegions()
|
||||
.map((r) => r.id)
|
||||
.map((r: CompareItem) => r.id)
|
||||
.sort()
|
||||
.join(',');
|
||||
if (fetchedR !== currentR) return true;
|
||||
@@ -173,7 +196,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
|
||||
if (kws.length > 0) {
|
||||
// Find existing selections that are still in keywords, or default to all
|
||||
const validSelections = currentSelections.filter((t) =>
|
||||
const validSelections = currentSelections.filter((t: string) =>
|
||||
kws.includes(t),
|
||||
);
|
||||
if (validSelections.length > 0) {
|
||||
@@ -188,6 +211,12 @@ export class UniTrendParentComponent implements OnInit {
|
||||
if (!active || !updatedSelections.includes(active)) {
|
||||
this.activeChartTopic.set(updatedSelections[0] || '');
|
||||
}
|
||||
|
||||
// If comparison list is empty, initialize default institutions dynamically
|
||||
const currentInsts = untracked(() => this.comparisonInstitutions());
|
||||
if (currentInsts.length === 0) {
|
||||
untracked(() => this.initializeDefaultInstitutions());
|
||||
}
|
||||
} else {
|
||||
this.selectedTrendTopics.set([]);
|
||||
}
|
||||
@@ -202,7 +231,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
const insts = Array.isArray(params['institutions'])
|
||||
? params['institutions']
|
||||
: [params['institutions']];
|
||||
const parsed = insts.map((i) => {
|
||||
const parsed = insts.map((i: string) => {
|
||||
const parts = i.split('|');
|
||||
return { id: parts[0], name: parts[1] || parts[0] };
|
||||
});
|
||||
@@ -213,7 +242,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
const ccs = Array.isArray(params['countries'])
|
||||
? params['countries']
|
||||
: [params['countries']];
|
||||
const parsed = ccs.map((c) => {
|
||||
const parsed = ccs.map((c: string) => {
|
||||
const parts = c.split('|');
|
||||
return { id: parts[0], name: parts[1] || parts[0] };
|
||||
});
|
||||
@@ -224,7 +253,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
const regs = Array.isArray(params['regions'])
|
||||
? params['regions']
|
||||
: [params['regions']];
|
||||
const parsed = regs.map((r) => {
|
||||
const parsed = regs.map((r: string) => {
|
||||
const parts = r.split('|');
|
||||
return { id: parts[0], name: parts[1] || parts[0] };
|
||||
});
|
||||
@@ -243,16 +272,69 @@ export class UniTrendParentComponent implements OnInit {
|
||||
if (params['active_chart_topic']) {
|
||||
this.activeChartTopic.set(params['active_chart_topic']);
|
||||
}
|
||||
|
||||
// Auto-trigger load once on initial page render if keywords are present
|
||||
if (this.rawTrendResponse() === null && this.keywords().length > 0) {
|
||||
this.fetchTrendData();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.loadTrendSuggestions();
|
||||
this.initializeDefaultInstitutions();
|
||||
}
|
||||
|
||||
// Dynamically load top institutions to initialize comparisons using the top-institutions service
|
||||
initializeDefaultInstitutions() {
|
||||
const kws = this.keywords();
|
||||
if (kws.length === 0) return;
|
||||
|
||||
const topic = kws[0];
|
||||
this.isSuggestionsLoading.set(true);
|
||||
|
||||
forkJoin({
|
||||
deInsts:
|
||||
this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
|
||||
topic,
|
||||
undefined,
|
||||
'DE',
|
||||
2,
|
||||
),
|
||||
overallInsts:
|
||||
this.apiService.getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(
|
||||
topic,
|
||||
undefined,
|
||||
undefined,
|
||||
2,
|
||||
),
|
||||
}).subscribe({
|
||||
next: ({
|
||||
deInsts,
|
||||
overallInsts,
|
||||
}: {
|
||||
deInsts: Array<TopInstitutionItem>;
|
||||
overallInsts: Array<TopInstitutionItem>;
|
||||
}) => {
|
||||
const uniqueInsts = new Map<string, string>();
|
||||
|
||||
// Add DE ones
|
||||
deInsts.forEach((inst: TopInstitutionItem) => {
|
||||
if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unknown');
|
||||
});
|
||||
|
||||
// Add overall ones
|
||||
overallInsts.forEach((inst: TopInstitutionItem) => {
|
||||
if (inst.id) uniqueInsts.set(inst.id, inst.display_name || 'Unknown');
|
||||
});
|
||||
|
||||
const list = Array.from(uniqueInsts.entries()).map(([id, name]) => ({
|
||||
id,
|
||||
name,
|
||||
}));
|
||||
this.comparisonInstitutions.set(list);
|
||||
this.isSuggestionsLoading.set(false);
|
||||
},
|
||||
error: (err: any) => {
|
||||
console.error('Failed to load default institutions dynamically:', err);
|
||||
this.isSuggestionsLoading.set(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch recommended institutions for comparison based on current topics
|
||||
@@ -268,11 +350,11 @@ export class UniTrendParentComponent implements OnInit {
|
||||
|
||||
const countryFilter =
|
||||
this.comparisonCountries().length > 0
|
||||
? this.comparisonCountries()[0].id.split('/').pop()
|
||||
? this.comparisonCountries()[0].id
|
||||
: undefined;
|
||||
const regionFilter =
|
||||
this.comparisonRegions().length > 0
|
||||
? this.comparisonRegions()[0].name
|
||||
? this.comparisonRegions()[0].id
|
||||
: undefined;
|
||||
|
||||
this.apiService
|
||||
@@ -283,7 +365,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
6,
|
||||
)
|
||||
.subscribe({
|
||||
next: (res) => {
|
||||
next: (res: any) => {
|
||||
this.topSuggestions.set(res || []);
|
||||
this.isSuggestionsLoading.set(false);
|
||||
},
|
||||
@@ -309,12 +391,12 @@ export class UniTrendParentComponent implements OnInit {
|
||||
this.apiService
|
||||
.getTrendApiInseServiceUniversityRankingsTrendGet(
|
||||
topics,
|
||||
this.comparisonInstitutions().map((i) => i.id),
|
||||
this.comparisonCountries().map((c) => c.id),
|
||||
this.comparisonRegions().map((r) => r.id),
|
||||
this.comparisonInstitutions().map((i: CompareItem) => i.id),
|
||||
this.comparisonCountries().map((c: CompareItem) => c.id),
|
||||
this.comparisonRegions().map((r: CompareItem) => r.id),
|
||||
)
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
next: (response: TrendResponse) => {
|
||||
this.rawTrendResponse.set(response);
|
||||
this.isTrendLoading.set(false);
|
||||
this.updateUrlParams();
|
||||
@@ -331,15 +413,21 @@ export class UniTrendParentComponent implements OnInit {
|
||||
trend_topics: this.selectedTrendTopics(),
|
||||
institutions:
|
||||
this.comparisonInstitutions().length > 0
|
||||
? this.comparisonInstitutions().map((i) => `${i.id}|${i.name}`)
|
||||
? this.comparisonInstitutions().map(
|
||||
(i: CompareItem) => `${i.id}|${i.name}`,
|
||||
)
|
||||
: null,
|
||||
countries:
|
||||
this.comparisonCountries().length > 0
|
||||
? this.comparisonCountries().map((c) => `${c.id}|${c.name}`)
|
||||
? this.comparisonCountries().map(
|
||||
(c: CompareItem) => `${c.id}|${c.name}`,
|
||||
)
|
||||
: null,
|
||||
regions:
|
||||
this.comparisonRegions().length > 0
|
||||
? this.comparisonRegions().map((r) => `${r.id}|${r.name}`)
|
||||
? this.comparisonRegions().map(
|
||||
(r: CompareItem) => `${r.id}|${r.name}`,
|
||||
)
|
||||
: null,
|
||||
start_year: this.startYear(),
|
||||
end_year: this.endYear(),
|
||||
@@ -364,7 +452,9 @@ export class UniTrendParentComponent implements OnInit {
|
||||
updated = current.includes(topic) ? current : [...current, topic];
|
||||
} else {
|
||||
updated =
|
||||
current.length > 1 ? current.filter((t) => t !== topic) : current;
|
||||
current.length > 1
|
||||
? current.filter((t: string) => t !== topic)
|
||||
: current;
|
||||
if (current.length === 1) {
|
||||
(event.target as HTMLInputElement).checked = true;
|
||||
}
|
||||
@@ -382,7 +472,10 @@ export class UniTrendParentComponent implements OnInit {
|
||||
// Add comparison institution
|
||||
addInstitution(id: string, name: string) {
|
||||
const current = this.comparisonInstitutions();
|
||||
if (!current.some((i) => i.id === id) && id !== this.primaryInstitution()) {
|
||||
if (
|
||||
!current.some((i: CompareItem) => i.id === id) &&
|
||||
id !== this.primaryInstitution()
|
||||
) {
|
||||
this.comparisonInstitutions.set([...current, { id, name }]);
|
||||
}
|
||||
this.searchQuery.set('');
|
||||
@@ -392,14 +485,16 @@ export class UniTrendParentComponent implements OnInit {
|
||||
// Remove comparison institution (data reuses instantly via computed)
|
||||
removeInstitution(id: string) {
|
||||
const current = this.comparisonInstitutions();
|
||||
this.comparisonInstitutions.set(current.filter((i) => i.id !== id));
|
||||
this.comparisonInstitutions.set(
|
||||
current.filter((i: CompareItem) => i.id !== id),
|
||||
);
|
||||
}
|
||||
|
||||
// Add country or region
|
||||
addLocation(loc: AutocompleteLocationItem) {
|
||||
if (loc.type === 'country') {
|
||||
const current = this.comparisonCountries();
|
||||
if (!current.some((c) => c.id === loc.id)) {
|
||||
if (!current.some((c: CompareItem) => c.id === loc.id)) {
|
||||
this.comparisonCountries.set([
|
||||
...current,
|
||||
{ id: loc.id, name: loc.display_name },
|
||||
@@ -407,7 +502,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
}
|
||||
} else if (loc.type === 'continent') {
|
||||
const current = this.comparisonRegions();
|
||||
if (!current.some((r) => r.id === loc.id)) {
|
||||
if (!current.some((r: CompareItem) => r.id === loc.id)) {
|
||||
this.comparisonRegions.set([
|
||||
...current,
|
||||
{ id: loc.id, name: loc.display_name },
|
||||
@@ -423,16 +518,20 @@ export class UniTrendParentComponent implements OnInit {
|
||||
removeLocation(id: string, type: 'country' | 'continent') {
|
||||
if (type === 'country') {
|
||||
const current = this.comparisonCountries();
|
||||
this.comparisonCountries.set(current.filter((c) => c.id !== id));
|
||||
this.comparisonCountries.set(
|
||||
current.filter((c: CompareItem) => c.id !== id),
|
||||
);
|
||||
} else if (type === 'continent') {
|
||||
const current = this.comparisonRegions();
|
||||
this.comparisonRegions.set(current.filter((r) => r.id !== id));
|
||||
this.comparisonRegions.set(
|
||||
current.filter((r: CompareItem) => r.id !== id),
|
||||
);
|
||||
}
|
||||
this.loadTrendSuggestions();
|
||||
}
|
||||
|
||||
// Scaling mode toggle (data reuses instantly)
|
||||
setChartMode(mode: 'normalized' | 'total') {
|
||||
setChartMode(mode: 'normalized' | 'total' | 'cumulative') {
|
||||
this.chartMode.set(mode);
|
||||
this.updateUrlParams();
|
||||
}
|
||||
@@ -450,7 +549,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
this.institutionsApiService
|
||||
.autocompleteInstitutions(query, undefined, 'education', 10)
|
||||
.subscribe({
|
||||
next: (res) => {
|
||||
next: (res: AutocompleteResponse) => {
|
||||
this.searchResults.set(res.results || []);
|
||||
},
|
||||
error: () => {
|
||||
@@ -471,7 +570,7 @@ export class UniTrendParentComponent implements OnInit {
|
||||
query,
|
||||
)
|
||||
.subscribe({
|
||||
next: (res) => {
|
||||
next: (res: AutocompleteLocationItem[]) => {
|
||||
this.locationSearchResults.set(res || []);
|
||||
},
|
||||
error: () => {
|
||||
|
||||
Reference in New Issue
Block a user