feat(news): expand search results to include similar results
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
||||
import httpx
|
||||
from .. import config
|
||||
|
||||
@@ -118,6 +118,93 @@ def search(
|
||||
return response.json()
|
||||
|
||||
|
||||
def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.post(
|
||||
f"{elasticsearch_url}/{index}/_pit",
|
||||
params={"keep_alive": keep_alive},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
"""Closes a previously opened point-in-time."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.request(
|
||||
"DELETE",
|
||||
f"{elasticsearch_url}/_pit",
|
||||
json={"id": pit_id},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
def scan(
|
||||
index: str,
|
||||
query: Dict,
|
||||
source: Optional[List] = None,
|
||||
page_size: int = 1000,
|
||||
keep_alive: str = "1m",
|
||||
cluster: str = "nes",
|
||||
) -> Iterator[Dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
pit_id = open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
search_after: Optional[List] = None
|
||||
try:
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
"size": page_size,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": keep_alive},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
"track_total_hits": False,
|
||||
}
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
|
||||
response = client.post(
|
||||
f"{elasticsearch_url}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
yield from hits
|
||||
|
||||
# The pit id can be refreshed between requests; keep the latest.
|
||||
pit_id = result.get("pit_id", pit_id)
|
||||
search_after = hits[-1].get("sort")
|
||||
if search_after is None or len(hits) < page_size:
|
||||
break
|
||||
finally:
|
||||
try:
|
||||
close_point_in_time(pit_id, cluster=cluster)
|
||||
except Exception:
|
||||
logger.exception("Failed to close Elasticsearch point-in-time.")
|
||||
|
||||
|
||||
def get(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
|
||||
@@ -20,6 +20,10 @@ TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
|
||||
|
||||
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
@@ -45,8 +49,9 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
"encoder": "html",
|
||||
}
|
||||
|
||||
exact_query = {"match": {"full_content": query_text}}
|
||||
response = _run_search(
|
||||
query={"match": {"full_content": query_text}},
|
||||
query=exact_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
@@ -54,7 +59,15 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = _build_page(response, page, page_size)
|
||||
|
||||
if _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = _exact_match_ids(exact_query)
|
||||
news_page.results.extend(
|
||||
_related_articles(query_text, exclude_ids=exclude_ids)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
def get_news_by_author(
|
||||
author_id: str,
|
||||
@@ -87,7 +100,17 @@ def get_news_by_author(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = _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)
|
||||
news_page.results.extend(
|
||||
_related_articles(
|
||||
query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
@@ -157,12 +180,17 @@ def _get_article_topics(maintitle: str | None, full_content: str | None) -> list
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
query_vector = get_model().encode(query).tolist()
|
||||
query_vector = get_model().encode(query_text).tolist()
|
||||
except Exception:
|
||||
logger.exception("Failed to encode news article text for topic search.")
|
||||
logger.exception("Failed to encode text for topic vector search.")
|
||||
return []
|
||||
|
||||
try:
|
||||
@@ -172,24 +200,20 @@ def _get_article_topics(maintitle: str | None, full_content: str | None) -> list
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": TOPIC_LIMIT,
|
||||
"k": k,
|
||||
"num_candidates": TOPIC_NUM_CANDIDATES,
|
||||
"similarity": TOPIC_SIMILARITY,
|
||||
},
|
||||
"_source": ["display_name"],
|
||||
"size": TOPIC_LIMIT,
|
||||
"_source": source_fields,
|
||||
"size": k,
|
||||
},
|
||||
cluster="nes",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Topic vector search for news article failed.")
|
||||
logger.exception("Topic vector search failed.")
|
||||
return []
|
||||
|
||||
return [
|
||||
display_name
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if (display_name := hit.get("_source", {}).get("display_name"))
|
||||
]
|
||||
return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
|
||||
|
||||
|
||||
def _build_mentioned_persons(author_names: list) -> list:
|
||||
@@ -321,3 +345,86 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
url=source.get("url"),
|
||||
snippet=snippet,
|
||||
)
|
||||
|
||||
|
||||
def _is_last_page(page: int, page_size: int, total: int) -> bool:
|
||||
return page * page_size >= total
|
||||
|
||||
|
||||
def _exact_match_ids(query: dict) -> list:
|
||||
try:
|
||||
response = _run_search(
|
||||
query=query,
|
||||
source=[],
|
||||
size=EXACT_ID_CAP,
|
||||
offset=0,
|
||||
sort=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to collect exact-match ids for dedup.")
|
||||
return []
|
||||
|
||||
return [
|
||||
hit.get("_id")
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if hit.get("_id")
|
||||
]
|
||||
|
||||
|
||||
def _related_articles(
|
||||
query_text: str,
|
||||
exclude_ids: list | None = None,
|
||||
filter_news_ids: list | None = None,
|
||||
k: int = RELATED_BLOCK_SIZE,
|
||||
) -> list:
|
||||
related_terms = _related_search_terms(query_text)
|
||||
if not related_terms:
|
||||
return []
|
||||
|
||||
bool_query = {
|
||||
"should": [{"match": {"full_content": term}} for term in related_terms],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
if exclude_ids:
|
||||
bool_query["must_not"] = [{"ids": {"values": exclude_ids}}]
|
||||
if filter_news_ids is not None:
|
||||
bool_query["filter"] = [{"ids": {"values": filter_news_ids}}]
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="aktuell",
|
||||
query={"bool": bool_query},
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=k,
|
||||
offset=0,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Related-articles search failed.")
|
||||
return []
|
||||
|
||||
articles = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
article = _parse_hit(hit)
|
||||
article.related = True
|
||||
articles.append(article)
|
||||
|
||||
relevance_map = _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"])
|
||||
|
||||
seen = {query_text.lower()}
|
||||
terms = []
|
||||
for topic in topics:
|
||||
for term in [topic.get("display_name"), *(topic.get("keywords") or [])]:
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
terms.append(term)
|
||||
|
||||
return terms
|
||||
|
||||
@@ -14,6 +14,7 @@ class NewsArticle(BaseModel):
|
||||
url: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
snippet: Optional[str] = None
|
||||
related: Optional[bool] = None
|
||||
|
||||
|
||||
class MentionedPerson(BaseModel):
|
||||
|
||||
@@ -31,6 +31,9 @@
|
||||
<a class="article-title" [routerLink]="['/news', article.id]">{{
|
||||
article.maintitle || 'Kein Titel'
|
||||
}}</a>
|
||||
@if (article.related) {
|
||||
<span class="related-badge"> Passend zu deiner Suche </span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
|
||||
@@ -79,6 +79,22 @@ table {
|
||||
}
|
||||
}
|
||||
|
||||
.related-badge {
|
||||
display: flex;
|
||||
width: fit-content;
|
||||
align-items: center;
|
||||
margin-top: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
background: #eef3fe;
|
||||
border: 1px solid #c5d6f7;
|
||||
color: #2f5bd0;
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface NewsArticleBase {
|
||||
maintitle?: string | null;
|
||||
url?: string | null;
|
||||
relevant?: boolean | null;
|
||||
related?: boolean | null;
|
||||
}
|
||||
|
||||
export type SortOrder = 'desc' | 'asc';
|
||||
|
||||
Reference in New Issue
Block a user