Add publication types and timespan filters to ranking queries and requests
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
Steven Tischer
2026-07-16 21:38:35 +02:00
parent ede9290643
commit e09a55fb52
6 changed files with 118 additions and 50 deletions
+45 -15
View File
@@ -116,16 +116,24 @@ def _yearly_works_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds a query that returns, per selected author, the year distribution of their topic works."""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
],
"filter": filters,
},
},
"aggs": {
@@ -176,6 +184,8 @@ async def yearly_works_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> List[AuthorYearlyWorks]:
"""For each selected author, returns the per-year count of their works on the topic.
@@ -186,7 +196,7 @@ async def yearly_works_for_authors(
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_yearly_works_query(author_ids, keywords, operator),
body=_yearly_works_query(author_ids, keywords, operator, publication_types, timespan),
cluster=ESCluster.NES,
)
@@ -228,16 +238,24 @@ def _corresponding_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds a query that counts, per selected author, the topic works where they are the corresponding author."""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
],
"filter": filters,
},
},
"aggs": {
@@ -284,6 +302,8 @@ async def corresponding_works_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> List[AuthorCorrespondingCount]:
"""For each selected author, counts the topic works where they are the corresponding author."""
if not author_ids:
@@ -291,7 +311,7 @@ async def corresponding_works_for_authors(
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_corresponding_query(author_ids, keywords, operator),
body=_corresponding_query(author_ids, keywords, operator, publication_types, timespan),
cluster=ESCluster.NES,
)
@@ -320,20 +340,28 @@ def _impact_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds a query with per-author citation-impact stats over their topic works.
The percentile fields live on the work (citation_normalized_percentile), so we
step back to the work level with reverse_nested before averaging / counting.
"""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
],
"filter": filters,
},
},
"aggs": {
@@ -395,6 +423,8 @@ async def impact_stats_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> List[AuthorImpactStats]:
"""For each selected author, returns citation-impact stats over their topic works."""
if not author_ids:
@@ -402,7 +432,7 @@ async def impact_stats_for_authors(
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_impact_query(author_ids, keywords, operator),
body=_impact_query(author_ids, keywords, operator, publication_types, timespan),
cluster=ESCluster.NES,
)
+8
View File
@@ -121,6 +121,14 @@ class SelectedAuthorsRequest(BaseModel):
default=KeywordOperator.AND,
description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.",
)
publication_types: List[PublicationType] = Field(
default_factory=list,
description="Optional filter: only count works of these publication types. Empty = no filter.",
)
timespan: Optional[Timespan] = Field(
default=None,
description="Optional filter: only count works whose publication_year is within [from, to].",
)
@field_validator("operator", mode="before")
@classmethod
+6
View File
@@ -57,6 +57,8 @@ async def rank_selected_author(request: SelectedAuthorsRequest):
request.author_ids,
request.keywords,
request.operator,
request.publication_types,
request.timespan,
)
@@ -72,6 +74,8 @@ async def corresponding_authors(request: SelectedAuthorsRequest):
request.author_ids,
request.keywords,
request.operator,
request.publication_types,
request.timespan,
)
@@ -87,4 +91,6 @@ async def impact_stats(request: SelectedAuthorsRequest):
request.author_ids,
request.keywords,
request.operator,
request.publication_types,
request.timespan,
)
@@ -21,4 +21,12 @@ export interface RankSelectedAuthorRequest {
* How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'.
*/
operator?: string;
/**
* Optional filter: only count works of these publication types.
*/
publication_types?: Array<string>;
/**
* Optional filter: only count works whose publication_year is within [from, to].
*/
timespan?: { from: number; to: number };
}
@@ -157,6 +157,9 @@ export class CompareAuthorsComponent implements OnInit {
// everything is read from the URL so a shared link lands on the same view
const rawAuthors = this.route.snapshot.queryParamMap.get('authors') ?? '';
const rawKeywords = this.route.snapshot.queryParamMap.get('keywords') ?? '';
const rawPubType = this.route.snapshot.queryParamMap.get('pubType');
const rawTFrom = this.route.snapshot.queryParamMap.get('tFrom');
const rawTTo = this.route.snapshot.queryParamMap.get('tTo');
const authorIds = this.parseList(rawAuthors);
const keywords = this.parseList(rawKeywords);
@@ -166,47 +169,54 @@ export class CompareAuthorsComponent implements OnInit {
return;
}
const publication_types = rawPubType
? this.parseList(rawPubType)
: undefined;
const timespan =
rawTFrom && rawTTo ? { from: +rawTFrom, to: +rawTTo } : undefined;
// ids in the url are bare (A5036...); the endpoint expects full OpenAlex urls
const fullIds = authorIds.map((id) => `https://openalex.org/${id}`);
const requestPayload = {
author_ids: fullIds,
keywords: keywords,
publication_types: publication_types,
timespan: timespan,
};
this.loading.set(true);
this.rankingService
.rankSelectedAuthor({ author_ids: fullIds, keywords: keywords })
.subscribe({
next: (results) => {
this.data.set(results);
this.loading.set(false);
},
error: (error) => {
console.error(error);
this.data.set([]);
this.loading.set(false);
},
});
this.rankingService.rankSelectedAuthor(requestPayload).subscribe({
next: (results) => {
this.data.set(results);
this.loading.set(false);
},
error: (error) => {
console.error(error);
this.data.set([]);
this.loading.set(false);
},
});
this.rankingService
.correspondingAuthors({ author_ids: fullIds, keywords: keywords })
.subscribe({
next: (results) => {
this.corresponding.set(results);
},
error: (error) => {
console.error(error);
this.corresponding.set([]);
},
});
this.rankingService.correspondingAuthors(requestPayload).subscribe({
next: (results) => {
this.corresponding.set(results);
},
error: (error) => {
console.error(error);
this.corresponding.set([]);
},
});
this.rankingService
.impactStats({ author_ids: fullIds, keywords: keywords })
.subscribe({
next: (results) => {
this.impact.set(results);
},
error: (error) => {
console.error(error);
this.impact.set([]);
},
});
this.rankingService.impactStats(requestPayload).subscribe({
next: (results) => {
this.impact.set(results);
},
error: (error) => {
console.error(error);
this.impact.set([]);
},
});
}
private parseList(raw: string): string[] {
@@ -306,6 +306,12 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
queryParams: {
authors: this.selectedIds().join(','),
keywords: this.state.keywords().join(','),
pubType:
this.selectedPubTypes().length > 0
? this.selectedPubTypes().join(',')
: null,
tFrom: this.timespanFrom(),
tTo: this.timespanTo(),
},
});
}