fix(keyword-search): add fuzzy search fallback for news

This commit is contained in:
2026-08-10 16:32:27 +02:00
parent c1692535a5
commit d8b7d8bc2e
5 changed files with 69 additions and 18 deletions
+17 -11
View File
@@ -153,12 +153,24 @@ async def search_news_by_keywords(
would leave every multi-keyword search empty.
Articles matching more of them simply rank higher.
A fuzzy search without any resolved topic ids falls back to the raw
keywords. Once there are topic ids the fallback is off: a topic search that matches no article
stays empty instead of silently returning keyword hits.
By default results stay ranked by match strength (Elasticsearch's
`_score`). Passing `sort_order` ('asc'/'desc') overrides that with a
plain date sort, same as the plain news list.
"""
wanted_topic_ids: set = set()
if fuzzy:
should = await _topic_id_should_clauses(topic_ids, filter_topic_ids)
wanted_topic_ids = {
topic_id
for topic_id in (topic_ids or []) + (filter_topic_ids or [])
if topic_id
}
if wanted_topic_ids:
should = await _topic_id_should_clauses(wanted_topic_ids)
else:
should = _keyword_should_clauses(keywords)
@@ -189,7 +201,7 @@ async def search_news_by_keywords(
size=page_size,
offset=(page - 1) * page_size,
sort=sort,
highlight=highlight if not fuzzy else None,
highlight=None if wanted_topic_ids else highlight,
)
news_page = await _build_page(response, page, page_size)
@@ -212,19 +224,13 @@ def _keyword_should_clauses(keywords: list | None) -> list:
]
async def _topic_id_should_clauses(
topic_ids: list | None, filter_topic_ids: list | None
) -> list:
async def _topic_id_should_clauses(topic_ids: set) -> list:
"""Turns matched OpenAlex topics into id clauses, boosted by hit count.
Articles that match several of the searched topics get a higher boost, so
Elasticsearch ranks them above articles that only match one.
"""
wanted = {tid for tid in (topic_ids or []) + (filter_topic_ids or []) if tid}
if not wanted:
return []
topics_per_article = await _news_ids_by_topic_ids(wanted)
topics_per_article = await _news_ids_by_topic_ids(topic_ids)
if not topics_per_article:
return []
@@ -715,7 +721,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s
return relevant, authors, keywords, hit.get("_id")
async 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 = None) -> dict:
try:
return await elasticsearch.search(
index="aktuell",