From 8becf406d61d4ac1a7ae23c06bbe9db1b9562809 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Mon, 20 Jul 2026 14:07:58 +0200 Subject: [PATCH] switch from keywords to topics (backend supports both) --- service/src/main/inse/ranking/logic.py | 84 ++++++++++++++----- service/src/main/inse/ranking/model.py | 24 +++++- service/src/main/inse/ranking/router.py | 8 +- .../app/api/model/keywordToAuthorRequest.ts | 4 + .../api/model/rankSelectedAuthorRequest.ts | 4 + .../compare-authors.component.ts | 3 +- .../persons-results.component.ts | 16 ++-- 7 files changed, 111 insertions(+), 32 deletions(-) diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 2c1adcc7..09363251 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -3,6 +3,7 @@ import asyncio import logging +from dataclasses import dataclass from time import time from typing import Any, List, Optional @@ -19,6 +20,7 @@ from .model import ( AuthorTopicStats, CareerStage, CompanyStatusFilter, + FilterType, KeywordOperator, PublicationType, RankedAuthor, @@ -67,27 +69,59 @@ async def _get_author_ids_from_uni(institution_name: str) -> List[str]: -def _keyword_clause(keyword: str) -> dict: - """A single nested clause that matches one keyword on a work.""" +@dataclass(frozen=True) +class MatchConfig: + """Where a topic filter matches on a work: keyword display names or topic ids.""" + + path: str + match_field: str + score_field: str + + +_KEYWORD_MATCH = MatchConfig( + path="keywords", + match_field="keywords.display_name.keyword", + score_field="keywords.score", +) +_TOPIC_MATCH = MatchConfig( + path="topics", + match_field="topics.display_name.keyword", + score_field="topics.score", +) + + +def _match_config(filter_type: FilterType) -> MatchConfig: + """Resolves the request's filter_type into the single set of fields to match on.""" + if filter_type == FilterType.TOPIC: + return _TOPIC_MATCH + return _KEYWORD_MATCH + + +def _keyword_clause(value: str, config: MatchConfig = _KEYWORD_MATCH) -> dict: + """A single nested clause that matches one keyword/topic value on a work.""" return { "nested": { - "path": "keywords", + "path": config.path, "query": { - "term": {"keywords.display_name.keyword": keyword}, + "term": {config.match_field: value}, }, }, } -def _build_keyword_query(keywords: List[str], operator: KeywordOperator) -> dict: - """Combines the keyword clauses according to the operator. +def _build_keyword_query( + keywords: List[str], + operator: KeywordOperator, + config: MatchConfig = _KEYWORD_MATCH, +) -> dict: + """Combines the keyword/topic clauses according to the operator. - AND: a work must carry all keywords (every clause is required). - OR: a work must carry at least one of the keywords. + AND: a work must carry all values (every clause is required). + OR: a work must carry at least one of the values. """ clauses = [] for keyword in keywords: - clauses.append(_keyword_clause(keyword)) + clauses.append(_keyword_clause(keyword, config)) if operator == KeywordOperator.OR: return { @@ -122,11 +156,12 @@ def _topic_stats_query( operator: KeywordOperator, publication_types: List[PublicationType], timespan: Optional[Timespan], + config: MatchConfig = _KEYWORD_MATCH, ) -> dict: """Builds a single query with all stats for Section 1""" filters = [ - _build_keyword_query(keywords, operator), + _build_keyword_query(keywords, operator, config), _author_filter(author_ids), ] @@ -203,33 +238,33 @@ def _topic_stats_query( "range": {"fwci": {"gt": 1}}, }, }, - # works whose matched keyword scores above 0.8 + # works whose matched keyword/topic scores above 0.8 "relevance_above_80": { "filter": { "nested": { - "path": "keywords", + "path": config.path, "query": { "bool": { "filter": [ - {"terms": {"keywords.display_name.keyword": keywords}}, - {"range": {"keywords.score": {"gt": 0.8}}}, + {"terms": {config.match_field: keywords}}, + {"range": {config.score_field: {"gt": 0.8}}}, ], }, }, }, }, }, - # average matched-keyword relevance score over the works + # average matched relevance score over the works "matched_keywords": { - "nested": {"path": "keywords"}, + "nested": {"path": config.path}, "aggs": { "only_searched": { "filter": { - "terms": {"keywords.display_name.keyword": keywords}, + "terms": {config.match_field: keywords}, }, "aggs": { "avg_score": { - "avg": {"field": "keywords.score"}, + "avg": {"field": config.score_field}, }, }, }, @@ -253,14 +288,18 @@ async def topic_stats_for_authors( operator: KeywordOperator, publication_types: List[PublicationType], timespan: Optional[Timespan], + filter_type: FilterType = FilterType.KEYWORD, ) -> List[AuthorTopicStats]: if not author_ids: return [] + match_cfg = _match_config(filter_type) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, - body=_topic_stats_query(author_ids, keywords, operator, publication_types, timespan), + body=_topic_stats_query( + author_ids, keywords, operator, publication_types, timespan, match_cfg + ), cluster=ESCluster.NES, ) @@ -397,10 +436,11 @@ def _build_query( author_ids: List[str], publication_types: List[PublicationType], timespan: Optional[Timespan], + config: MatchConfig = _KEYWORD_MATCH, ) -> dict: """Builds the Elasticsearch query that returns the raw stats per author.""" work_filters = [ - _build_keyword_query(keywords, operator), + _build_keyword_query(keywords, operator, config), _author_filter(author_ids), ] if publication_types: @@ -753,6 +793,7 @@ async def rank_authors_by_keywords( publication_types: List[PublicationType], timespan: Optional[Timespan], company_status: CompanyStatusFilter = CompanyStatusFilter.ALL, + filter_type: FilterType = FilterType.KEYWORD, ) -> List[RankedAuthor]: """Ranks the university's authors by a weighted score over works and citations. @@ -770,7 +811,8 @@ async def rank_authors_by_keywords( author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages) query_body = _build_query( - keywords, operator, author_ids, publication_types, timespan + keywords, operator, author_ids, publication_types, timespan, + _match_config(filter_type), ) response: dict[str, Any] = await elasticsearch.search( diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index 2c2b61a1..2fff9f15 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -14,6 +14,11 @@ class KeywordOperator(StrEnum): OR = "or" +class FilterType(StrEnum): + KEYWORD = "keyword" + TOPIC = "topic" + + class CompanyStatusFilter(StrEnum): ALL = "all" ACTIVE = "active" @@ -104,6 +109,11 @@ class KeywordToAuthorRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) + filter_type: FilterType = Field( + default=FilterType.KEYWORD, + description="What the 'keywords' values match against: 'keyword' (OpenAlex " + "keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.", + ) institution_name: str = Field( default="University of Duisburg-Essen", description="The selected institution display name. (Default Uni-Due)", @@ -129,7 +139,7 @@ class KeywordToAuthorRequest(BaseModel): "'all', only 'active' (non-deleted), or only 'deleted'.", ) - @field_validator("operator", mode="before") + @field_validator("operator", "filter_type", mode="before") @classmethod def operator_case_insensitive(cls, value): if isinstance(value, str): @@ -150,6 +160,11 @@ class SelectedAuthorsRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) + filter_type: FilterType = Field( + default=FilterType.KEYWORD, + description="What the 'keywords' values match against: 'keyword' (OpenAlex " + "keyword display names) or 'topic' (OpenAlex topic ids). Defaults to 'keyword'.", + ) publication_types: List[PublicationType] = Field( default_factory=list, description="Optional filter: only count works of these publication types. Empty = no filter.", @@ -166,6 +181,13 @@ class SelectedAuthorsRequest(BaseModel): return value.lower() return value + @field_validator("filter_type", mode="before") + @classmethod + def filter_type_case_insensitive(cls, value): + if isinstance(value, str): + return value.lower() + return value + class AuthorMetricsRequest(BaseModel): author_ids: List[str] = Field( diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index 79db8e17..d79c85ea 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -25,10 +25,11 @@ router = APIRouter( @router.post("/rank-author", response_model=List[RankedAuthor]) async def rank_author(request: KeywordToAuthorRequest): logger.info( - "rank-author keywords=%s operator=%s institution_name=%s career_stages=%s " + "rank-author keywords=%s operator=%s filter_type=%s institution_name=%s career_stages=%s " "publication_types=%s timespan=%s", request.keywords, request.operator, + request.filter_type, request.institution_name, request.career_stages, request.publication_types, @@ -43,16 +44,18 @@ async def rank_author(request: KeywordToAuthorRequest): request.publication_types, request.timespan, request.company_status, + request.filter_type, ) # Compare authors table 1 (topic stats) @router.post("/topic-stats", response_model=List[AuthorTopicStats]) async def topic_stats(request: SelectedAuthorsRequest): logger.info( - "topic-stats author_ids=%s keywords=%s operator=%s publication_types=%s timespan=%s", + "topic-stats author_ids=%s keywords=%s operator=%s filter_type=%s publication_types=%s timespan=%s", request.author_ids, request.keywords, request.operator, + request.filter_type, request.publication_types, request.timespan, ) @@ -62,6 +65,7 @@ async def topic_stats(request: SelectedAuthorsRequest): request.operator, request.publication_types, request.timespan, + request.filter_type, ) # Compare authors table 2 (author-level stats, keyword/time-independent) diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts index 4910ce89..9d34e1d9 100644 --- a/webapp/src/app/api/model/keywordToAuthorRequest.ts +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -22,6 +22,10 @@ export interface KeywordToAuthorRequest { * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. */ operator?: string; + /** + * What the \'keywords\' values match against: \'keyword\' or \'topic\'. Defaults to \'keyword\'. + */ + filter_type?: string; /** * The selected institution display name. (Default Uni-Due) */ diff --git a/webapp/src/app/api/model/rankSelectedAuthorRequest.ts b/webapp/src/app/api/model/rankSelectedAuthorRequest.ts index c3454ea5..6119e974 100644 --- a/webapp/src/app/api/model/rankSelectedAuthorRequest.ts +++ b/webapp/src/app/api/model/rankSelectedAuthorRequest.ts @@ -21,6 +21,10 @@ export interface RankSelectedAuthorRequest { * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. */ operator?: string; + /** + * What the \'keywords\' values match against: \'keyword\' or \'topic\'. Defaults to \'keyword\'. + */ + filter_type?: string; /** * Optional filter: only count works of these publication types. */ diff --git a/webapp/src/app/modules/compare-authors/compare-authors.component.ts b/webapp/src/app/modules/compare-authors/compare-authors.component.ts index d2272b8b..1a91057f 100644 --- a/webapp/src/app/modules/compare-authors/compare-authors.component.ts +++ b/webapp/src/app/modules/compare-authors/compare-authors.component.ts @@ -281,7 +281,7 @@ export class CompareAuthorsComponent implements OnInit { return; } - const operator = rawOperator === 'or' ? 'or' : 'and'; + const operator = rawOperator === 'and' ? 'and' : 'or'; const publication_types = rawPubType ? this.parseList(rawPubType) : undefined; @@ -300,6 +300,7 @@ export class CompareAuthorsComponent implements OnInit { author_ids: fullIds, keywords: keywords, operator: operator, + filter_type: 'topic', publication_types: publication_types, timespan: timespan, }) diff --git a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts index f827ba08..e0bea4d1 100644 --- a/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/persons-results/persons-results.component.ts @@ -238,14 +238,14 @@ export class KeywordsToPersonsResultsComponent implements OnInit { { value: 'or', label: 'ODER' }, ]; - readonly keywordOperator = signal<'and' | 'or'>('and'); + readonly keywordOperator = signal<'and' | 'or'>('or'); onKeywordOperatorChange(operator: 'and' | 'or'): void { this.keywordOperator.set(operator); this.router.navigate([], { relativeTo: this.route, queryParams: { - operator: operator === 'and' ? null : operator, + operator: operator, page: null, }, queryParamsHandling: 'merge', @@ -291,8 +291,8 @@ export class KeywordsToPersonsResultsComponent implements OnInit { this.careerStages.set(careerStage.split(',')); } const operator = this.route.snapshot.queryParamMap.get('operator'); - if (operator === 'or') { - this.keywordOperator.set('or'); + if (operator === 'and' || operator === 'or') { + this.keywordOperator.set(operator); } } @@ -422,8 +422,8 @@ export class KeywordsToPersonsResultsComponent implements OnInit { this.router.navigate(['/compare'], { queryParams: { authors: this.selectedIds().join(','), - keywords: this.state.keywords().join(','), - operator: this.keywordOperator() === 'or' ? 'or' : null, + keywords: this.state.topicsList().join(','), + operator: this.keywordOperator(), pubType: this.selectedPubTypes().length > 0 ? this.selectedPubTypes().join(',') @@ -436,9 +436,11 @@ export class KeywordsToPersonsResultsComponent implements OnInit { private loadAuthors(): void { const rawWeights = this.currentWeights().raw; + const request: KeywordToAuthorRequest = { - keywords: this.state.keywords(), + keywords: this.state.topicsList(), operator: this.keywordOperator(), + filter_type: 'topic', publication_types: this.selectedPubTypes().length > 0 ? this.selectedPubTypes()