switch from keywords to topics (backend supports both)
This commit is contained in:
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
*/
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
+9
-7
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user