updated publications fetching logic

This commit is contained in:
2026-07-16 22:36:26 +02:00
parent 03627bdb00
commit 6a94153b22
3 changed files with 127 additions and 112 deletions
+18 -46
View File
@@ -74,53 +74,23 @@ async def get_author_works(
summary="Search works by topics or raw keywords with filters."
)
async def search_works_by_keywords(
topics: Annotated[
topics: Annotated[list[str] | None, Query(description="List of topics to match.")] = None,
topic_ids: Annotated[list[str] | None, Query(description="List of topic IDs to match.")] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(description="List of topics to match."),
Query(description="Additional topic IDs to filter results by, independent of search mode."),
] = None,
topic_ids: Annotated[
list[str] | None,
Query(description="List of topic IDs to match."),
] = None,
keywords: Annotated[
list[str] | None,
Query(description="Raw keywords to search in title/abstract."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Use topic resolution if True, otherwise use raw keywords."),
] = True,
publication_year: Annotated[
list[int] | None,
Query(description="A list of publication years to filter by."),
] = None,
publication_type: Annotated[
list[str] | None,
Query(description="A list of publication types to filter by."),
] = None,
institution_ids: Annotated[
list[str] | None,
Query(description="A list of institution IDs to filter by."),
] = None,
language: Annotated[
list[str] | None,
Query(description="A list of language codes to filter by."),
] = None,
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=1)
] = 1,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
keywords: Annotated[list[str] | None, Query(description="Raw keywords to search in title/abstract.")] = None,
fuzzy: Annotated[bool, Query(description="Use topic resolution if True, otherwise use raw keywords.")] = True,
publication_year: Annotated[list[int] | None, Query(description="A list of publication years to filter by.")] = None,
publication_type: Annotated[list[str] | None, Query(description="A list of publication types to filter by.")] = None,
institution_ids: Annotated[list[str] | None, Query(description="A list of institution IDs to filter by.")] = None,
language: Annotated[list[str] | None, Query(description="A list of language codes to filter by.")] = None,
page: Annotated[int, Query(description="The page number to retrieve. (0-based)", ge=0)] = 0,
size: Annotated[int, Query(description="The number of works to retrieve per page.", ge=1, le=100)] = 10,
sort_by: Annotated[WorkSortBy, Query(description="The field to sort by.")] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[SortDirection, Query(description="The order to sort by.")] = SortDirection.DESCENDING,
) -> WorkPage:
print(topics, keywords, fuzzy, publication_year, publication_type, institution_ids, topic_ids, language, page, size, sort_by, sort_order)
return await get_works_by_keywords(
topics=topics or [],
keywords=keywords or [],
@@ -129,12 +99,14 @@ async def search_works_by_keywords(
publication_type=publication_type or [],
institution_ids=institution_ids or [],
topic_ids=topic_ids or [],
filter_topic_ids=filter_topic_ids or [],
language=language or [],
page=page,
size=size,
sort_by=sort_by,
sort_order=sort_order)
sort_order=sort_order,
)
@router.get(
"/topics/search",
operation_id="getWorkTopicsByIds",
+98 -62
View File
@@ -103,7 +103,9 @@ async def get_author_works(
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for author {raw_oa_author_id} v2: {source}")
work = Work.from_dict(source) # type: ignore
if work is not None:
elements.append(work)
return WorkPage(
@@ -165,45 +167,59 @@ async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Insti
institutions.append(Institution.from_dict(source)) # type: ignore
return institutions
async def get_works_by_keywords(
topics: Optional[List[str]] = Query(None, description="List of topics to match."),
topic_ids: Optional[List[str]] = Query(None, description="List of topic IDs to match."),
filter_topic_ids: Optional[List[str]] = Query(
None,
description="Additional topic IDs to filter results by (OR semantics), "
"applied independently of the fuzzy/keyword search mode.",
),
keywords: Optional[List[str]] = Query(None, description="Raw keywords to search in title/abstract."),
fuzzy: bool = Query(True, description="Use topic resolution if True, otherwise use raw keywords."),
publication_year: Optional[List[int]] = Query(None),
publication_type: Optional[List[str]] = Query(None, alias="type"),
language: Optional[List[str]] = Query(None),
institution_ids: Optional[List[str]] = Query(None),
page: int = 1,
page: int = 0,
size: int = 10,
sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR),
sort_order: SortDirection = Query(SortDirection.DESCENDING),
):
# 1. Build the Topic/Keyword Clause
) -> WorkPage:
print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}")
def _topics_nested_clause(should_clauses: List[Dict]) -> Dict:
return {
"nested": {
"path": "topics",
"query": {
"bool": {
"should": should_clauses,
"minimum_should_match": 1,
}
},
"score_mode": "max",
}
}
def _single_topic_id_match(topic_id: str) -> Dict:
return {
"bool": {
"should": [
_topics_nested_clause([{"term": {"topics.id": topic_id}}]),
{"term": {"primary_topic.id": topic_id}},
],
"minimum_should_match": 1,
}
}
topic_clause = None
if fuzzy and topic_ids:
resolved_ids = topic_ids
if resolved_ids:
topic_clause = {
"bool": {
"should": [
{"nested": {"path": "topics", "query": {"terms": {"topics.id": resolved_ids}}}},
{"terms": {"primary_topic.id": resolved_ids}},
],
"minimum_should_match": 1,
}
}
elif topics:
# Fallback to match_phrase if resolution failed
topic_clause = {
"bool": {
"should": [{"match_phrase": {"primary_topic.display_name": t}} for t in topics],
"minimum_should_match": 1,
}
}
filter_on_ids = list(set(topic_ids + filter_topic_ids))
topic_clause = {
"bool": {"must": [_single_topic_id_match(tid) for tid in filter_on_ids]}
}
elif keywords:
# Raw keyword matching across multiple fields
keyword_clauses = []
for kw in keywords:
keyword_clauses.append({
@@ -213,6 +229,12 @@ async def get_works_by_keywords(
{"match_phrase": {"primary_topic.display_name": kw}},
{"match_phrase": {"title": kw}},
{"match_phrase": {"abstract": kw}},
_topics_nested_clause([
{"match_phrase": {"topics.display_name": kw}},
{"match_phrase": {"topics.field.display_name": kw}},
{"match_phrase": {"topics.subfield.display_name": kw}},
{"match_phrase": {"topics.domain.display_name": kw}},
]),
],
"minimum_should_match": 1,
}
@@ -220,12 +242,21 @@ async def get_works_by_keywords(
topic_clause = {"bool": {"must": keyword_clauses}}
if not topic_clause:
# If no search criteria provided, we might want to return an error or all works.
# For this implementation, we'll return an empty page or a default search.
return WorkPage(elements=[], total=0, page=page, size=size)
# 2. Build Filters
#filters
must = [topic_clause]
# independent, additive topic filter — always applied,
# regardless of fuzzy/keyword search mode.
# if filter_topic_ids:
# must.append({
# "bool": {
# "should": [_single_topic_id_match(tid) for tid in filter_topic_ids],
# "minimum_should_match": 1,
# }
# })
if publication_year:
must.append({"terms": {"publication_year": publication_year}})
if publication_type:
@@ -235,56 +266,61 @@ async def get_works_by_keywords(
if institution_ids:
must.append({
"nested": {
"path": "authorships.institutions",
"query": {"terms": {"authorships.institutions.id": institution_ids}}
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {"terms": {"authorships.institutions.id": institution_ids}},
}
},
}
})
# 3. Execute Search
sort = [{sort_by.value: "desc"}] if sort_by != WorkSortBy.TITLE else [{"title.keyword": "asc"}]
#sorting
if sort_by == WorkSortBy.TITLE:
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
#search
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=[
"id", "title", "type", "publication_year", "language",
"cited_by_count", "authorships.institutions.id",
"authorships.institutions.display_name", "authorships.institutions.country_code", "topics"
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"abstract",
"keywords",
"primary_topic",
"authorships.author",
"authorships.institutions.id",
"authorships.institutions.display_name",
"authorships.institutions.country_code",
"topics",
],
query={"bool": {"must": must}},
size=size,
offset=(page - 1) * size,
track_total_hits=True,
offset=page * size,
sort=sort,
cluster=ESCluster.NES,
)
# 4. Map to Model (Reusing logic from v2 service)
logger.debug(f"Query: {{'bool': {{'must': {must}}}}}")
#model mapping
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
hits = hits_block.get("hits", [])
elements = []
elements: List[Work] = []
for hit in hits:
source = hit.get("_source", {})
institutions = {}
for authorship in source.get("authorships", []):
for inst in authorship.get("institutions", []):
i_id = inst.get("id", "")
if i_id not in institutions:
institutions[i_id] = Institution(
institution_id=i_id,
institution_name=inst.get("display_name", ""),
institution_country_code=inst.get("country_code", ""),
)
topics_list = [WorkTopic.from_dict(t) for t in source.get("topics", [])]
elements.append(Work(
id=source.get("id", ""),
title=source.get("title", ""),
type=source.get("type", ""),
publication_year=source.get("publication_year", 0),
language_code=source.get("language") or "",
institutions=list(institutions.values()),
topics=topics_list,
cited_by_count=source.get("cited_by_count", 0),
))
logger.debug(f"Hit source for keyword search: {source}")
return WorkPage(elements=elements, total=total, page=page, size=size)
work = Work.from_dict(source) # type: ignore
if work is not None:
elements.append(work)
return WorkPage(elements=elements, total=total, page=page, size=size)
+11 -4
View File
@@ -277,6 +277,7 @@ export class WorksV2Service extends BaseService {
* @endpoint get /api/v2/works/keyword/search
* @param topics List of topics to match.
* @param topicIds List of topic IDs to match.
* @param filterTopicIds Additional topic IDs to filter results by, independent of search mode.
* @param keywords Raw keywords to search in title/abstract.
* @param fuzzy Use topic resolution if True, otherwise use raw keywords.
* @param publicationYear A list of publication years to filter by.
@@ -290,10 +291,10 @@ export class WorksV2Service extends BaseService {
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseWorksV2ModelWorkPage>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseWorksV2ModelWorkPage>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseWorksV2ModelWorkPage>>;
public getWorksByKeywords(topics?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, keywords?: Array<string>, fuzzy?: boolean, publicationYear?: Array<number>, publicationType?: Array<string>, institutionIds?: Array<string>, language?: Array<string>, page?: number, size?: number, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (topics) {
@@ -308,6 +309,12 @@ export class WorksV2Service extends BaseService {
<any>element, 'topic_ids');
})
}
if (filterTopicIds) {
filterTopicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'filter_topic_ids');
})
}
if (keywords) {
keywords.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,