Replaced httpx in ipc_search_client, adjusted synchronous calls to use async await in logic
This commit is contained in:
@@ -62,7 +62,7 @@ async def get_funders_by_author_id(
|
||||
funder_counts: dict[str, dict[str, Any]] = {}
|
||||
|
||||
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
|
||||
author_name = _get_author_name(author_id)
|
||||
author_name = await _get_author_name(author_id)
|
||||
|
||||
try:
|
||||
_, all_hits = await _fetch_all_author_work_hits(
|
||||
@@ -180,9 +180,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
return total, results
|
||||
|
||||
|
||||
def _get_author_name(author_id: str) -> str | None:
|
||||
async def _get_author_name(author_id: str) -> str | None:
|
||||
short_author_id = author_id.replace("https://openalex.org/", "")
|
||||
search_result = person_logic.search_persons(author_id=short_author_id)
|
||||
search_result = await person_logic.search_persons(author_id=short_author_id)
|
||||
|
||||
if not search_result.results:
|
||||
return None
|
||||
|
||||
@@ -41,7 +41,7 @@ _VALID_INSTITUTION_TYPES = {
|
||||
async def get_institution_by_id(
|
||||
raw_institution_id: str, client: InstitutionsSearchClient
|
||||
) -> Institution:
|
||||
return client.get_institution_by_id(raw_institution_id)
|
||||
return await client.get_institution_by_id(raw_institution_id)
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
@@ -120,7 +120,7 @@ async def autocomplete_institutions(
|
||||
Returns institution options for autocomplete inputs using the local
|
||||
Elasticsearch cluster via the provided client.
|
||||
"""
|
||||
institutions = client.search_institutions(
|
||||
institutions = await client.search_institutions(
|
||||
query_text=query,
|
||||
country_code=country_code,
|
||||
institution_type=institution_type,
|
||||
|
||||
@@ -72,7 +72,7 @@ async def search_institutions_by_name(
|
||||
),
|
||||
] = "asc",
|
||||
) -> InstitutionPage:
|
||||
return client.get_institutions_by_name(
|
||||
return await client.get_institutions_by_name(
|
||||
name=name,
|
||||
page=page,
|
||||
size=size,
|
||||
|
||||
@@ -36,7 +36,7 @@ RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
|
||||
|
||||
def get_news_page(
|
||||
async def get_news_page(
|
||||
page: int,
|
||||
page_size: int,
|
||||
sort_order: str = "desc",
|
||||
@@ -46,10 +46,10 @@ def get_news_page(
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
clauses = _filter_clauses(year_from, year_to, relevance_values)
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}}
|
||||
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=page_size,
|
||||
@@ -57,10 +57,10 @@ def get_news_page(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
return await _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def search_news(
|
||||
async def search_news(
|
||||
query_text: str,
|
||||
page: int,
|
||||
page_size: int,
|
||||
@@ -78,14 +78,14 @@ def search_news(
|
||||
}
|
||||
|
||||
# Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
|
||||
clauses = _filter_clauses(year_from, year_to, relevance_values)
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
exact_query = {
|
||||
"bool": {
|
||||
"must": [{"match": {"full_content": query_text}}],
|
||||
"filter": clauses,
|
||||
}
|
||||
}
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=exact_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
@@ -94,19 +94,20 @@ def search_news(
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
news_page = _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
if _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = _exact_match_ids(exact_query)
|
||||
exclude_ids = await _exact_match_ids(exact_query)
|
||||
news_page.results.extend(
|
||||
_related_articles(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, extra_filters=clauses
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
def get_news_by_author(
|
||||
|
||||
async def get_news_by_author(
|
||||
author_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
@@ -114,11 +115,11 @@ def get_news_by_author(
|
||||
query_text: str | None = None,
|
||||
) -> NewsPage:
|
||||
|
||||
author_name = get_author_name_by_id(author_id)
|
||||
author_name = await get_author_name_by_id(author_id)
|
||||
if not author_name:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
news_ids = _find_news_ids_for_author(author_name)
|
||||
news_ids = await _find_news_ids_for_author(author_name)
|
||||
if not news_ids:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
@@ -129,7 +130,7 @@ def get_news_by_author(
|
||||
]
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=es_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
@@ -137,12 +138,12 @@ def get_news_by_author(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
news_page = _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
if query_text and _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = _exact_match_ids(es_query)
|
||||
exclude_ids = await _exact_match_ids(es_query)
|
||||
news_page.results.extend(
|
||||
_related_articles(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
|
||||
)
|
||||
)
|
||||
@@ -150,7 +151,7 @@ def get_news_by_author(
|
||||
return news_page
|
||||
|
||||
|
||||
def _filter_clauses(
|
||||
async def _filter_clauses(
|
||||
year_from: int | None,
|
||||
year_to: int | None,
|
||||
relevance_values: list | None,
|
||||
@@ -165,14 +166,14 @@ def _filter_clauses(
|
||||
date_range["lte"] = year_to
|
||||
clauses.append({"range": {"date_year": date_range}})
|
||||
|
||||
relevant_ids = _relevance_news_ids(relevance_values)
|
||||
relevant_ids = await _relevance_news_ids(relevance_values)
|
||||
if relevant_ids is not None:
|
||||
clauses.append({"ids": {"values": relevant_ids}})
|
||||
|
||||
return clauses
|
||||
|
||||
|
||||
def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
async def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
selected = set(relevance_values or [])
|
||||
|
||||
if not selected or {"relevant", "not_relevant"} <= selected:
|
||||
@@ -182,7 +183,7 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
|
||||
news_ids = []
|
||||
try:
|
||||
for hit in elasticsearch.scan(
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"relevant": relevant_value}},
|
||||
source=["news_id"],
|
||||
@@ -198,10 +199,10 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
return news_ids
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
async def _find_news_ids_for_author(author_name: str) -> list:
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"authors.keyword": author_name}},
|
||||
source=["news_id"],
|
||||
@@ -225,9 +226,9 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
|
||||
return NewsPage(total=0, page=page, page_size=page_size, results=[])
|
||||
|
||||
|
||||
def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
try:
|
||||
response = elasticsearch.get(
|
||||
response = await elasticsearch.get(
|
||||
index="aktuell",
|
||||
doc_id=news_id,
|
||||
source=["date", "maintitle", "author", "url", "full_content"],
|
||||
@@ -242,9 +243,9 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors, cached_keywords, postproc_id = _get_postproc_labels(news_id)
|
||||
topics = _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = _get_article_keywords(
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
cached_keywords,
|
||||
@@ -260,24 +261,24 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
url=source.get("url"),
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=_build_mentioned_persons(authors),
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
)
|
||||
|
||||
|
||||
def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
def _get_article_keywords(
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
cached_keywords: list,
|
||||
@@ -301,7 +302,7 @@ def _get_article_keywords(
|
||||
keywords = _parse_keywords(raw)
|
||||
|
||||
if keywords:
|
||||
_store_keywords(news_id, postproc_id, keywords)
|
||||
await _store_keywords(news_id, postproc_id, keywords)
|
||||
|
||||
return keywords
|
||||
|
||||
@@ -326,17 +327,17 @@ def _parse_keywords(raw: str) -> list:
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
try:
|
||||
if postproc_id:
|
||||
elasticsearch.update(
|
||||
await elasticsearch.update(
|
||||
index="aktuell_postproc",
|
||||
doc_id=postproc_id,
|
||||
doc={"keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
else:
|
||||
elasticsearch.index_doc(
|
||||
await elasticsearch.index_doc(
|
||||
index="aktuell_postproc",
|
||||
doc_id=news_id,
|
||||
document={"news_id": news_id, "keywords": keywords},
|
||||
@@ -346,7 +347,7 @@ def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> No
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
@@ -356,7 +357,7 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
return []
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body={
|
||||
"knn": {
|
||||
@@ -378,13 +379,13 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
|
||||
|
||||
|
||||
def _build_mentioned_persons(author_names: list) -> list:
|
||||
async def _build_mentioned_persons(author_names: list) -> list:
|
||||
|
||||
ude_persons = []
|
||||
other_persons = []
|
||||
|
||||
for name in author_names:
|
||||
match = find_ude_author_by_name(name)
|
||||
match = await find_ude_author_by_name(name)
|
||||
if match:
|
||||
ude_persons.append(
|
||||
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
|
||||
@@ -395,9 +396,9 @@ def _build_mentioned_persons(author_names: list) -> list:
|
||||
return ude_persons + other_persons
|
||||
|
||||
|
||||
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
|
||||
async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"news_id.keyword": news_id}},
|
||||
source=["relevant", "authors", "keywords"],
|
||||
@@ -421,9 +422,9 @@ def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | N
|
||||
return relevant, authors, keywords, hit.get("_id")
|
||||
|
||||
|
||||
def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
||||
try:
|
||||
return elasticsearch.search(
|
||||
return await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query=query,
|
||||
source=source,
|
||||
@@ -442,7 +443,7 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig
|
||||
) from exc
|
||||
|
||||
|
||||
def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
hits_section = response.get("hits", {})
|
||||
total = hits_section.get("total", {}).get("value", 0)
|
||||
hits = hits_section.get("hits", [])
|
||||
@@ -453,7 +454,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
|
||||
relevance_map = _get_relevance_map(news_ids)
|
||||
relevance_map = await _get_relevance_map(news_ids)
|
||||
|
||||
articles = []
|
||||
for hit in hits:
|
||||
@@ -469,12 +470,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
)
|
||||
|
||||
|
||||
def _get_relevance_map(news_ids: list) -> dict:
|
||||
async def _get_relevance_map(news_ids: list) -> dict:
|
||||
if not news_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"terms": {"news_id.keyword": news_ids}},
|
||||
source=["news_id", "relevant"],
|
||||
@@ -499,7 +500,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
|
||||
|
||||
if fragments:
|
||||
snippet = fragments[0]
|
||||
else:
|
||||
@@ -517,7 +518,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
|
||||
def _make_preview(source: dict) -> str | None:
|
||||
text = source.get("intro_content") or source.get("full_content")
|
||||
|
||||
|
||||
if not text:
|
||||
return None
|
||||
|
||||
@@ -534,9 +535,9 @@ def _is_last_page(page: int, page_size: int, total: int) -> bool:
|
||||
return page * page_size >= total
|
||||
|
||||
|
||||
def _exact_match_ids(query: dict) -> list:
|
||||
async def _exact_match_ids(query: dict) -> list:
|
||||
try:
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=[],
|
||||
size=EXACT_ID_CAP,
|
||||
@@ -554,14 +555,14 @@ def _exact_match_ids(query: dict) -> list:
|
||||
]
|
||||
|
||||
|
||||
def _related_articles(
|
||||
async def _related_articles(
|
||||
query_text: str,
|
||||
exclude_ids: list | None = None,
|
||||
filter_news_ids: list | None = None,
|
||||
extra_filters: list | None = None,
|
||||
k: int = RELATED_BLOCK_SIZE,
|
||||
) -> list:
|
||||
related_terms = _related_search_terms(query_text)
|
||||
related_terms = await _related_search_terms(query_text)
|
||||
if not related_terms:
|
||||
return []
|
||||
|
||||
@@ -577,7 +578,7 @@ def _related_articles(
|
||||
bool_query.setdefault("filter", []).extend(extra_filters)
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query={"bool": bool_query},
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
@@ -595,15 +596,15 @@ def _related_articles(
|
||||
article.related = True
|
||||
articles.append(article)
|
||||
|
||||
relevance_map = _get_relevance_map([article.id for article in articles])
|
||||
relevance_map = await _get_relevance_map([article.id for article in articles])
|
||||
for article in articles:
|
||||
article.relevant = relevance_map.get(article.id)
|
||||
|
||||
return articles
|
||||
|
||||
|
||||
def _related_search_terms(query_text: str) -> list:
|
||||
topics = _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
|
||||
async def _related_search_terms(query_text: str) -> list:
|
||||
topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
|
||||
|
||||
seen = {query_text.lower()}
|
||||
terms = []
|
||||
|
||||
@@ -34,7 +34,7 @@ def _parse_relevance(relevance: str | None) -> list:
|
||||
summary="Returns a page of news articles, newest first.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def list_news(
|
||||
async def list_news(
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
@@ -54,7 +54,7 @@ def list_news(
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_page(
|
||||
return await logic.get_news_page(
|
||||
page,
|
||||
page_size,
|
||||
sort_order,
|
||||
@@ -72,7 +72,7 @@ def list_news(
|
||||
summary="Searches news articles by full text (full_content).",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def search_news(
|
||||
async def search_news(
|
||||
query: Annotated[
|
||||
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
|
||||
],
|
||||
@@ -92,7 +92,7 @@ def search_news(
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.search_news(
|
||||
return await logic.search_news(
|
||||
query,
|
||||
page,
|
||||
page_size,
|
||||
@@ -110,7 +110,7 @@ def search_news(
|
||||
summary="Returns news articles in which the given person is mentioned.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_author(
|
||||
async def get_news_by_author(
|
||||
author_id: Annotated[
|
||||
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
|
||||
],
|
||||
@@ -127,7 +127,7 @@ def get_news_by_author(
|
||||
str | None, Query(description="Optional search term, matched against title/author.")
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
return await logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -138,9 +138,9 @@ def get_news_by_author(
|
||||
summary="Returns a single news article including its full content.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_id(
|
||||
async def get_news_by_id(
|
||||
news_id: Annotated[
|
||||
str, Path(description="The unique id of the news article (Elasticsearch _id).")
|
||||
],
|
||||
):
|
||||
return logic.get_news_by_id(news_id)
|
||||
return await logic.get_news_by_id(news_id)
|
||||
|
||||
@@ -16,6 +16,9 @@ from .ipc_lookup import IpcHierarchyKeys
|
||||
from .ipc_lookup import build_ipc_classification
|
||||
from .ipc_lookup import parse_ipc_symbol
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
IPC_INDEX = "ipc"
|
||||
|
||||
_LEVELS: tuple[tuple[str, str, str], ...] = (
|
||||
@@ -136,15 +139,4 @@ class IpcSearchClient:
|
||||
return found
|
||||
|
||||
async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{IPC_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE)
|
||||
|
||||
@@ -55,7 +55,7 @@ async def get_patents_by_author_id(
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = _get_author(author_id)
|
||||
author = await _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
@@ -250,9 +250,9 @@ def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||
)
|
||||
|
||||
|
||||
def _get_author(author_id: str) -> Author | None:
|
||||
async def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = person_logic.search_persons(author_id=short_id)
|
||||
result = await person_logic.search_persons(author_id=short_id)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
|
||||
@@ -357,7 +357,7 @@ async def vector_search_topics(
|
||||
}
|
||||
|
||||
try:
|
||||
raw_results = elasticsearch.search(
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body=body,
|
||||
cluster="nes"
|
||||
|
||||
@@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran
|
||||
|
||||
|
||||
# Fetch top institutions for the topic by works_count
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=10,
|
||||
|
||||
@@ -148,7 +148,7 @@ async def get_primary_topic_counts(
|
||||
return result
|
||||
|
||||
|
||||
def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
@@ -174,11 +174,11 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except Exception as exc:
|
||||
logger.exception("OpenAlex primary topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
@@ -212,18 +212,18 @@ async def get_work(
|
||||
return elements[0]
|
||||
|
||||
|
||||
def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
if not topic_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"terms": {"id": topic_ids}},
|
||||
source=TOPIC_DETAIL_SOURCE_FIELDS,
|
||||
size=len(topic_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic details from Elasticsearch.")
|
||||
return {}
|
||||
|
||||
@@ -242,7 +242,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
"domain": _extract_topic_hierarchy_item(source, "domain"),
|
||||
}
|
||||
|
||||
_enrich_topic_hierarchy_descriptions(details)
|
||||
await _enrich_topic_hierarchy_descriptions(details)
|
||||
|
||||
return details
|
||||
|
||||
@@ -260,7 +260,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non
|
||||
}
|
||||
|
||||
|
||||
def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
|
||||
hierarchy_ids = {
|
||||
item.get(hierarchy_key, {}).get("id")
|
||||
@@ -268,7 +268,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
if item.get(hierarchy_key, {}).get("id")
|
||||
}
|
||||
|
||||
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
|
||||
for item in details.values():
|
||||
hierarchy_item = item.get(hierarchy_key) or {}
|
||||
@@ -278,7 +278,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
hierarchy_item["description"] = descriptions[hierarchy_id]
|
||||
|
||||
|
||||
def _get_topic_hierarchy_descriptions(
|
||||
async def _get_topic_hierarchy_descriptions(
|
||||
index: str,
|
||||
hierarchy_ids: list[str],
|
||||
) -> dict[str, str | None]:
|
||||
@@ -286,13 +286,13 @@ def _get_topic_hierarchy_descriptions(
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
query={"terms": {"id": hierarchy_ids}},
|
||||
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
|
||||
size=len(hierarchy_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic hierarchy details from %s.", index)
|
||||
return {}
|
||||
|
||||
@@ -433,7 +433,7 @@ async def get_topics_by_time_by_author(
|
||||
client=client,
|
||||
)
|
||||
|
||||
return _get_topics_by_time_by_author_from_es(
|
||||
return await _get_topics_by_time_by_author_from_es(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
target_publications=target_publications,
|
||||
@@ -521,7 +521,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
if topic["id"]:
|
||||
topic_ids.add(topic["id"])
|
||||
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = []
|
||||
|
||||
@@ -580,13 +580,13 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
)
|
||||
|
||||
|
||||
def _get_topics_by_time_by_author_from_es(
|
||||
async def _get_topics_by_time_by_author_from_es(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
) -> TopicsByTime:
|
||||
year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
|
||||
year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id)
|
||||
selected_years, is_limited = _select_complete_timeline_years(
|
||||
year_buckets,
|
||||
target_publications=target_publications,
|
||||
@@ -602,13 +602,13 @@ def _get_topics_by_time_by_author_from_es(
|
||||
total_publications=total_publications,
|
||||
)
|
||||
|
||||
year_topic_buckets = _get_timeline_topic_counts_from_es(
|
||||
year_topic_buckets = await _get_timeline_topic_counts_from_es(
|
||||
author_id,
|
||||
years=selected_years,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets)
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = _build_timeline_elements_from_aggregations(
|
||||
year_topic_buckets,
|
||||
@@ -625,7 +625,7 @@ def _get_topics_by_time_by_author_from_es(
|
||||
)
|
||||
|
||||
|
||||
def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
body = {
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
@@ -642,11 +642,11 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except Exception as exc:
|
||||
logger.exception("OpenAlex publication year aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
@@ -656,7 +656,7 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in
|
||||
return _parse_year_count_buckets(response), _parse_total_hits(response)
|
||||
|
||||
|
||||
def _get_timeline_topic_counts_from_es(
|
||||
async def _get_timeline_topic_counts_from_es(
|
||||
author_id: str,
|
||||
years: list[int],
|
||||
max_topics_per_year: int,
|
||||
@@ -713,11 +713,11 @@ def _get_timeline_topic_counts_from_es(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except Exception as exc:
|
||||
logger.exception("OpenAlex timeline topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
@@ -954,7 +954,7 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
return elements, total
|
||||
|
||||
|
||||
def get_publication_dois_of_author(
|
||||
async def get_publication_dois_of_author(
|
||||
raw_oa_author_id: str,
|
||||
) -> List[str]:
|
||||
query = {
|
||||
@@ -976,14 +976,14 @@ def get_publication_dois_of_author(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-works",
|
||||
source=["doi"],
|
||||
size=10000,
|
||||
query=query,
|
||||
cluster="nes",
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except Exception as exc:
|
||||
logger.exception("Request for publication DOIs of author failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
|
||||
Reference in New Issue
Block a user